var webDevice = 'pc';
var radarAddress = '';
var animationAddress = ''
var webSocketUrl = '';
var sessionID = '';
var switchLine = [];
var defaultType = '';
var ballType = '';
var ballFunc = '';
var nowDate = {
    "string": "",
    "object": {}
};
var gameDate = {
    "string": "",
    "object": {}
};
var favoriteSetting;
var leagueArray = {
    'withSID': [],
    'withoutSID': []
};
var sortOption = {
    "status": 'All',
    "orderBy": 1,
    'league': ['All']
};
var orderByForChangeType = {
    "bb": 0,
    "tw": 0,
    "bk": 0,
    "af": 0,
    "ih": 0,
    "sc": 1,
    "tn": 0,
    "vl": 0,
    "bv": 0,
    "hb": 0,
    "es": 0,
    "bm": 0,
    "fv": 1
};
var soccerCards = {
    "yellowCard": 1,
    "stadings": 1,
    "corner": 1,
    "announces": 1
};
var gameMarked = {
    "checked": [],
    "inTop": [],
    "inKeep": [],
    "inExclude": []
};
var viewPosition = 0;
var isRecover = true;
var isLastPack = false;
var recentSN = 0;
var recentCommand = '';
var recordPLCount = 0;
var updateItem = {};
var lightScanner = {
    'timer': null,
    'actionRecord': {}
};
var scheduleData = {};
var allianceData = {};
var scheduleArray = {};
var tempScheduleData = {};
var scheduleDelay = {
    'timer': null,
    'array': [],
    'index': 0
};
var windowScroll = {
    'X': $(window).scrollLeft(),
    'Y': $(window).scrollTop()
};
var lastTouchEnd = 0;
$(document).ready(function() {
    Mask();
    if (window.top.location != window.self.location) {
        $('body').hide();
        return;
    }
    GetUrlParam();
    $.ajax({
        type: 'POST',
        url: '/ajax/AjaxLog.aspx',
        data: {
            method: 'GetAppSettings',
            value: 'main'
        },
        dataType: 'json',
        success: function(data) {
            radarAddress = $.base64.atob(data['RadarAddress'], true);
            animationAddress = $.base64.atob(data['AnimationAddress'], true);
            webSocketUrl = $.base64.atob(data['WebSocketUrl'], true).split(',');
            sessionID = 'Web_main_' + $.base64.atob(data['SessionID'], true);
            switchLine = $.base64.atob(data['SwitchLine'], true).split(',');
            var html = '';
            var isRoute = false;
            var routeClass = '';
            for (var i = 0; i < switchLine.length; i++) {
                if (!isRoute && location.href.indexOf(switchLine[i].substr(0, switchLine[i].indexOf('.'))) >= 0) {
                    routeClass = 'onPage';
                    isRoute = true;
                } else {
                    routeClass = '';
                }
                html += '<li id="route' + (i + 1) + '" class="' + routeClass + '">' + '<a href="' + switchLine[i] + '?device=pc">' + langFont['Font_Route'] + (i + 1) + '</a></li>';
            }
            $('#routeOption').html(html);
            recentCommand = {
                'action': 'first',
                'language': langFont['Font_Langue'],
                'system': 'Web_main',
                'token': sessionID
            };
            ballType = urlParam['ball'];
            if (ballType) {
                recentCommand['ball'] = ballType;
            }
            if (FuncInterface.WebSocketTest()) {
                FuncInterface.SocketConnect('Web_main', '', '', sessionID);
            } else {
                FuncInterface.BindFlash('Web_main', '', '', sessionID);
            }
        }
    });
    $('#msgClose').click(function() {
        $('#scheduleRemind').addClass('hidden');
    });
    $('#scheduleBlock > div.scrollbar-inner').scroll(ScrollPage);
    var _addEventListener = '';
    var sys = '';
    if (window.addEventListener) {
        _addEventListener = "addEventListener";
    } else {
        _addEventListener = "attachEvent";
    }
    if (document.onmousewheel === null && window.addEventListener === undefined) {
        wheel_event_name = 'onmousewheel';
    } else if ( !! window.WheelEvent && !!window.MouseWheelEvent) {
        wheel_event_name = 'wheel';
    } else if ( !! window.WheelEvent) {
        if ('onmousewheel' in window) {
            wheel_event_name = 'mousewheel';
            sys = 'chrome';
        } else if ('addEventListener' in window) {
            wheel_event_name = 'wheel';
            sys = 'firefox';
        }
    } else {
        wheel_event_name = 'DOMMouseScroll';
    }
    document[_addEventListener](wheel_event_name,
    function(e) {
        var delta = 0;
        if (sys == 'firefox') {
            delta = e.deltaY * 40;
        } else if (sys == 'chrome') {
            delta = -e.wheelDeltaY;
        } else {
            delta = e.deltaY;
        }
        if (e.target.parentElement.tagName == 'BODY') {
            $('#scheduleBlock > div > div').scrollTop($('#scheduleBlock > div > div').scrollTop() + delta);
        }
    });
    $(document).click(listEvent);
    document.addEventListener("touchend",
    function(event) {
        listEvent(event);
        var now = Date.now();
        if (now - lastTouchEnd <= 300) {
            event.preventDefault();
        }
        lastTouchEnd = now;
    },
    false);
    $('#leagueOption').draggabilly({
        containment: true,
        handle: '#leagueTitle,#allLeague,#leagueFooter',
        click: '#optionArea .optionItem,#leagueTitle > input[name="close"],#leagueFooter > input[name="submit"]'
    });
    $('#scheduleRemind').addClass('hidden');
    $('#langType').html($('#btn' + langFont['Font_Langue'].toUpperCase()).text() + '<img src="/images/sport/ic_arrowB_top.png" />');
    $('#btn' + langFont['Font_Langue'].toUpperCase()).parent().addClass('onPage');
    $(document).on('mouseover', '#scheduleBlock > div > div > div > table > tbody > tr',
    function() {
        var gid = $(this).attr('gid');
        $('#' + gid + '_mainRow').addClass('hover');
        $('#' + gid + '_secondRow').addClass('hover');
        $('#' + gid + '_scoreBottom').addClass('hover');
        $('#' + gid + '_notice').addClass('hover');
    });
    $(document).on('mouseout', '#scheduleBlock table tr',
    function() {
        var gid = $(this).attr('gid');
        $('#' + gid + '_mainRow').removeClass('hover');
        $('#' + gid + '_secondRow').removeClass('hover');
        $('#' + gid + '_scoreBottom').removeClass('hover');
        $('#' + gid + '_notice').removeClass('hover');
    });
    $("#menuList").scrollbar({
        'disableBodyScroll': true
    });
    $('#scheduleBlock > div.scrollbar-inner').scrollbar();
    $(window).resize(function() {
        var width = $(window).width();
        var scrollLeft = $(window).scrollLeft();
        var scrollTop = $(window).scrollTop();
        if ($('#scheduleRemind:visible').length) {
            var positionLeft = 0;
            var positionTop = 120;
            $('#scheduleRemind').removeAttr('style');
            if (width < 600) {
                $('#scheduleRemind').css('min-width', 340);
            }
            if (width < 1200) {
                var maxWidth = width - 60;
                if (scrollLeft < 200 && $('#scheduleRemind').width() + 60 > width - (200 - scrollLeft)) {
                    $('#scheduleRemind').css('max-width', maxWidth - (200 - scrollLeft));
                } else {
                    $('#scheduleRemind').css('max-width', maxWidth);
                }
            }
            if (width < 1200) {
                positionLeft = scrollLeft + (width - $('#scheduleRemind').width()) / 2;
            } else {
                positionLeft = scrollLeft + $('#scheduleBlock').offset().left + ($('#scheduleBlock').width() - $('#scheduleRemind').width()) / 2;
            }
            if (scrollTop > 80) {
                positionTop = 120 + scrollTop - 80;
            }
            positionLeft = positionLeft < 230 ? 230 : positionLeft;
            $('#scheduleRemind').offset({
                top: positionTop,
                left: positionLeft
            });
        }
        $('#lockUI').css('height', $(window).height() + 1000).css('width', $(window).width() + 1000).css('top', -500).css('left', -500) $('body').height($(window).height());
        if (width <= 1230) {
            var left = width < 1205 ? 1190 : width - 15;
            $('#hideSetting').add('#scheduleTop').add('#scheduleMiddle').add('#scheduleBottom').add('#fixedTitle').css('width', 985);
            $('#scheduleBlock .scrollbar-inner > .scroll-y').css('left', 990).css('top', 0).css('position', 'absolute').css('height', '100%');
        } else {
            $('#fixedTitle').css('width', '100%');
            $('#hideSetting').removeAttr('style');
            $('#scheduleBlock .scrollbar-inner > .scroll-y').removeAttr('style');
            $('#scheduleTop').add('#scheduleMiddle').add('#scheduleBottom').removeAttr('style');
        }
    });
    $(window).scroll(function() {
        var width = $(window).width();
        var scrollLeft = $(window).scrollLeft();
        var scrollTop = $(window).scrollTop();
        if ($('#scheduleRemind:visible').length) {
            if (scrollLeft != windowScroll['X']) {
                var positionLeft = (width - $('#scheduleRemind').width()) / 2;
                var maxWidth = width - 60;
                if (scrollLeft < 200) {
                    $('#scheduleRemind').css('max-width', maxWidth - 200 + scrollLeft);
                    if (width >= 1200) {
                        positionLeft = $('#scheduleBlock').offset().left + ($('#scheduleBlock').width() - $('#scheduleRemind').width()) / 2;
                    }
                } else {
                    $('#scheduleRemind').css('max-width', maxWidth);
                }
                positionLeft += scrollLeft;
                positionLeft = positionLeft < 230 ? 230 : positionLeft;
                $('#scheduleRemind').offset({
                    left: positionLeft
                });
            }
            if (scrollTop != windowScroll['Y']) {
                var positionTop = 120;
                if (scrollTop > 80) {
                    positionTop = 120 + scrollTop - 80;
                }
                $('#scheduleRemind').offset({
                    top: positionTop
                });
            }
        }
        windowScroll['X'] = scrollLeft;
        windowScroll['Y'] = scrollTop;
    });
    $(window).resize();
});
function listEvent(e) {
    if ($(e.target).attr('id') != 'chooseDate' && $(e.target).parents('#chooseDate').length == 0) {
        $('#dateOption').hide();
    }
    if ($(e.target).attr('id') != 'soccerDisplay' && $(e.target).parents('#soccerDisplay').length == 0) {
        $('#soccerOption').hide();
    }
    if ($(e.target).attr('id') != 'ddlRoute' && $(e.target).parents('#ddlRoute').length == 0) {
        $('#routeOption').hide();
    }
    if ($(e.target).attr('id') != 'ddlLang' && $(e.target).parents('#ddlLang').length == 0) {
        $('#langOption').hide();
    }
    if ($(e.target).attr('id') != 'ddlOrderBy' && $(e.target).parents('#ddlOrderBy').length == 0) {
        $('#orderByOption').hide();
    }
};
function ActionFirst(data) {
    $('#logoBlock').show();
    $('#content').show();
    if ($('#soccerOption').outerWidth() < $('#soccerDisplay').outerWidth() + 7) {
        $('#soccerOption').width($('#soccerDisplay').outerWidth() + 7);
    }
    recentSN = data['sn'];
    defaultType = data['type'];
    ballType = data['type'];
    var tempDate = new Date(data['date'].split(' ')[0]);
    var monthStr = tempDate.getMonth() + 1;
    monthStr = monthStr < 10 ? "0" + monthStr: monthStr;
    var dateStr = tempDate.getDate() < 10 ? "0" + tempDate.getDate() : tempDate.getDate();
    nowDate['string'] = tempDate.getFullYear() + '/' + monthStr + '/' + dateStr;
    nowDate['object'] = new Date(nowDate['string']);
    gameDate = $.extend({},
    nowDate);
    var getDate = ballType == 'fv' ? 'fv': ballType + '_' + gameDate['string'].substr(5, 5);
    var getLeagueOption = GetCookie(getDate).split(',');
    if (getLeagueOption != '') {
        sortOption['league'] = [];
        sortOption['league'] = sortOption['league'].concat(getLeagueOption);
    }
    $('#ddlOrderBy > ul > li').removeClass('onPage');
    sortOption['orderBy'] = orderByForChangeType[ballType];
    var orderByString = sortOption['orderBy'] == 1 ? [langFont['Font_OrderTime'], 'last-child'] : [langFont['Font_OrderLeague'], 'first-child'];
    $('#ddlOrderBy > span').html(orderByString[0] + '<img src="/images/sport/ic_arrowB_white.png" />');
    $('#ddlOrderBy > ul > li:' + orderByString[1]).addClass('onPage');
    if (data['PLCount']) {
        recordPLCount = data['PLCount'];
    } else {
        recordPLCount = 0;
    }
    var fvPk = [];
    var fvDate = [];
    $.each(data["fvPK"],
    function(e) {
        var array = data["fvPK"][e].splice(',');
        for (var i = 0; i < array.length; i++) {
            fvDate.push(e);
            fvPk.push(array[i]);
        }
    });
    fvPk = fvPk.length > 0 ? fvPk: FuncInterface.cookieFvPk;
    fvDate = fvDate.length > 0 ? fvDate: FuncInterface.cookieFvDate;
    if (fvPk.length > 0) {
        FuncFavorite.ScheduleFVGroup['pk'] = fvPk;
        FuncFavorite.ScheduleFVGroup['date'] = fvDate;
        SetCookie('fvPK', FuncFavorite.ScheduleFVGroup['pk']);
        SetCookie('fvDate', FuncFavorite.ScheduleFVGroup['date']);
    }
    DrawMenuList(data['menu'], ballType);
    favoriteSetting = data['fvSetting'];
    favoriteSetting['title'] = document.title;
    if (ballType == 'sc') {
        updateItem['#goalMsg'] = {
            'time': null,
            'prompt': []
        };
    }
    recentCommand = {
        'action': 'ct',
        'type': ballType,
        'date': gameDate['string'].replaceAll('/', ''),
        'order': sortOption['orderBy']
    };
    $('#goalMsg').empty();
    $('#scheduleTop').add('#scheduleMiddle').add('#scheduleBottom').empty();
    SetDateOption(data['gameCount']['date']);
    leagueArray = {
        'withSID': [],
        'withoutSID': []
    };
    allianceData = {};
    scheduleData = {};
    for (var i = 0; i < data['league'].length; i++) {
        var leagueInfo = data['league'][i];
        var leagueID = leagueInfo['id'];
        allianceData[leagueID] = leagueInfo;
        leagueArray['withoutSID'].push(leagueID);
    }
    leagueArray['withSID'] = $.extend([], leagueArray['withoutSID']).sort(function(a, b) {
        if (allianceData[a]['s'] != allianceData[b]['s']) {
            return allianceData[a]['s'] > allianceData[b]['s'] ? 1 : -1;
        } else {
            return $.inArray(a, leagueArray['withoutSID']) > $.inArray(b, leagueArray['withoutSID']) ? 1 : -1;
        }
    });
    var packSchedule = InitialCache(data['schedule']);
    $('#leagueOption').offset({
        top: -500,
        left: -500
    });
    $('#boundary').show();
    SetLeagueOption();
    $('#boundary').hide();
    $('#leagueOption').removeAttr('style');
    ShowOrHideElement();
    var filterData = FilterSchedule(ballType, packSchedule, allianceData, 1);
    scheduleDelay['array'] = $.isEmptyObject(filterData) ? filterData: SplitScheduleHtml(filterData);
    scheduleDelay['index'] = 0;
    isLastPack = scheduleDelay['array'].length == 1 && recordPLCount == 0 ? true: false;
    DrawSchedule(scheduleDelay['array'][0], ballType, isLastPack, false);
    if ($('#scheduleTop').add('#scheduleMiddle').add('#scheduleBottom').children('table').length > 0) {
        UnMask();
    }
    scheduleDelay['timer'] = setInterval(function() {
        scheduleDelay['index'] = scheduleDelay['index'] + 1;
        if (scheduleDelay['index'] < scheduleDelay['array'].length) {
            isLastPack = scheduleDelay['array'].length == scheduleDelay['index'] + 1 && recordPLCount == 0 ? true: false;
            DrawSchedule(scheduleDelay['array'][scheduleDelay['index']], ballType, isLastPack, false);
        } else {
            window.clearInterval(scheduleDelay['timer']);
            scheduleDelay['index'] = 0;
            scheduleDelay['array'] = [];
            if (recordPLCount == 0) {
                isRecover = true;
                isLastPack = false;
                UnMask();
            }
            var json = {
                'action': data['action'] + '_over',
                'syn': data['syn']
            };
            FuncInterface.SendCommand(json);
        }
    },
    100);
}
function ActionFirstContinue(data) {
    recentSN = data['sn'];
    var packSchedule = InitialCache(data['schedule']);
    var filterData = FilterSchedule(ballType, packSchedule, allianceData, 2);
    scheduleDelay['array'] = $.isEmptyObject(filterData) ? filterData: SplitScheduleHtml(filterData);
    isLastPack = recordPLCount == parseInt(data['action'].substr(5, 1), 10) && scheduleDelay['array'].length > 1 ? true: false;
    DrawSchedule(scheduleDelay['array'][0], ballType, isLastPack, false);
    if ($('#scheduleTop').add('#scheduleMiddle').add('#scheduleBottom').children('table').length > 0) {
        UnMask();
    }
    scheduleDelay['timer'] = setInterval(function() {
        scheduleDelay['index'] = scheduleDelay['index'] + 1;
        if (scheduleDelay['index'] < scheduleDelay['array'].length) {
            isLastPack = scheduleDelay['array'].length == scheduleDelay['index'] + 1 && recordPLCount == parseInt(data['action'].substr(5, 1), 10) ? true: false;
            DrawSchedule(scheduleDelay['array'][scheduleDelay['index']], ballType, isLastPack, false);
        } else {
            window.clearInterval(scheduleDelay['timer']);
            scheduleDelay['index'] = 0;
            scheduleDelay['array'] = [];
            if (recordPLCount == parseInt(data['action'].substr(5, 1), 10)) {
                isRecover = true;
                isLastPack = false;
                UnMask();
            }
            var json = {
                'action': data['action'] + '_over',
                'syn': data['syn']
            };
            FuncInterface.SendCommand(json);
        }
    },
    100);
}
function ActionChangeType(data) {
    recentSN = data['sn'];
    ballType = data['type'];
    $('#scheduleRemind').addClass('hidden');
    if (ballType != 'sc') {
        $('#fixedTitle').hide();
        delete updateItem['#goalMsg'];
    } else {
        updateItem['#goalMsg'] = {
            'time': null,
            'prompt': []
        };
    }
    $('#ddlOrderBy > ul > li').removeClass('onPage');
    sortOption['orderBy'] = orderByForChangeType[ballType];
    var orderByString = sortOption['orderBy'] == 1 ? [langFont['Font_OrderTime'], 'last-child'] : [langFont['Font_OrderLeague'], 'first-child'];
    $('#ddlOrderBy > span').html(orderByString[0] + '<img src="/images/sport/ic_arrowB_white.png" />');
    $('#ddlOrderBy > ul > li:' + orderByString[1]).addClass('onPage');
    viewPosition = $('#scheduleBlock > div > div').scrollTop();
    var getDate = ballType == 'fv' ? 'fv': ballType + '_' + gameDate['string'].substr(5, 5);
    var getLeagueOption = GetCookie(getDate).split(',');
    if (getLeagueOption != '') {
        sortOption['league'] = [];
        sortOption['league'] = sortOption['league'].concat(getLeagueOption);
    } else {
        sortOption['league'] = ['All'];
    }
    leagueArray = {
        'withSID': [],
        'withoutSID': []
    };
    allianceData = {};
    scheduleData = {};
    if (isRecover == false) {
        gameMarked['checked'] = [];
        gameMarked['inExclude'] = [];
        gameMarked['inKeep'] = [];
        gameMarked['isKeep'] = false;
        gameMarked['inTop'] = [];
        $('#fixedTitle > span.check > span').removeClass('ckbOK');
        $('#scheduleTop').add('#scheduleMiddle').add('#scheduleBottom').empty();
    }
    if (data['PLCount']) {
        recordPLCount = data['PLCount'];
    } else {
        recordPLCount = 0;
    }
    for (var i = 0; i < data['league'].length; i++) {
        var leagueInfo = data['league'][i];
        var leagueID = leagueInfo['id'];
        allianceData[leagueID] = leagueInfo;
        leagueArray['withoutSID'].push(leagueID);
    }
    leagueArray['withSID'] = $.extend([], leagueArray['withoutSID']).sort(function(a, b) {
        if (allianceData[a]['s'] != allianceData[b]['s']) {
            return allianceData[a]['s'] > allianceData[b]['s'] ? 1 : -1;
        } else {
            return $.inArray(a, leagueArray['withoutSID']) > $.inArray(b, leagueArray['withoutSID']) ? 1 : -1;
        }
    });
    var packSchedule = InitialCache(data['schedule']);
    $('#leagueOption').offset({
        top: -500,
        left: -500
    });
    $('#boundary').show();
    SetLeagueOption();
    $('#boundary').hide();
    $('#leagueOption').removeAttr('style');
    if (ballType != 'fv') {
        DrawMenuList(data['menu'], ballType);
        SetDateOption(data['gameCount']['date']);
    }
    if (data['fvPK']) {
        for (var i = 0; i < FuncFavorite.ScheduleFVGroup['pk'].length; i++) {
            if (JSON.stringify(data['fvPK']).indexOf(FuncFavorite.ScheduleFVGroup['pk'][i]) < 0) {
                FuncFavorite.ScheduleFVGroup['pk'].remove(FuncFavorite.ScheduleFVGroup['pk'][i]);
                FuncFavorite.ScheduleFVGroup['date'].remove(FuncFavorite.ScheduleFVGroup['date'][i]);
            }
        }
    }
    if (isRecover == false) {
        if (ballType == 'fv') {
            ShowOrHideElement();
            DrawMenuList('menuDetailModify', 'fv');
            FuncFavorite.DrawFavoriteSchedule(scheduleData, allianceData, leagueArray['withoutSID'], true);
            isRecover = true;
            isLastPack = false;
            $('#scheduleBlock > div > div').scrollTop(viewPosition);
            GameMarked();
            UnMask();
            var json = {
                'action': data['action'] + '_over',
                'syn': data['syn']
            };
            FuncInterface.SendCommand(json);
        } else {
            ShowOrHideElement();
            var filterData = FilterSchedule(ballType, packSchedule, allianceData, 1);
            scheduleDelay['array'] = $.isEmptyObject(filterData) ? filterData: SplitScheduleHtml(filterData);
            scheduleDelay['index'] = 0;
            isLastPack = scheduleDelay['array'].length == 1 && recordPLCount == 0 ? true: false;
            DrawSchedule(scheduleDelay['array'][0], ballType, isLastPack, false);
            if ($('#scheduleTop').add('#scheduleMiddle').add('#scheduleBottom').children('table').length > 0) {
                UnMask();
            }
            scheduleDelay['timer'] = setInterval(function() {
                scheduleDelay['index'] = scheduleDelay['index'] + 1;
                if (scheduleDelay['index'] < scheduleDelay['array'].length) {
                    isLastPack = scheduleDelay['array'].length == scheduleDelay['index'] + 1 && recordPLCount == 0 ? true: false;
                    DrawSchedule(scheduleDelay['array'][scheduleDelay['index']], ballType, isLastPack, false);
                } else {
                    window.clearInterval(scheduleDelay['timer']);
                    scheduleDelay['index'] = 0;
                    scheduleDelay['array'] = [];
                    if (recordPLCount == 0) {
                        isRecover = true;
                        isLastPack = false;
                        $('#scheduleBlock > div > div').scrollTop(viewPosition);
                        GameMarked();
                        UnMask();
                    }
                    var json = {
                        'action': data['action'] + '_over',
                        'syn': data['syn']
                    };
                    FuncInterface.SendCommand(json);
                }
            },
            100);
        }
    } else {
        if (recordPLCount == 0) {
            if (ballType == 'fv') {
                FuncFavorite.DrawFavoriteSchedule(scheduleData, allianceData, leagueArray['withoutSID'], true);
            } else {
                var filterData = FilterSchedule(ballType, scheduleData, allianceData, 1);
                DrawSchedule(filterData, ballType, true, true);
            }
            isRecover = true;
            isLastPack = false;
            if ((ballType == 'fv' || ballType == 'sc') && $('#scheduleTop > table').length > 0) {
                $('#scheduleMiddle > table.scTable').addClass('scTop');
            }
            $('#scheduleBlock > div > div').scrollTop(viewPosition);
            GameMarked();
            UnMask();
        }
        var json = {
            'action': data['action'] + '_over',
            'syn': data['syn']
        };
        FuncInterface.SendCommand(json);
    }
}
function ActionChangeTypeContinue(data) {
    recentSN = data['sn'];
    var packSchedule = InitialCache(data['schedule']);
    if (isRecover == false) {
        var filterData = FilterSchedule(ballType, packSchedule, allianceData, 2);
        scheduleDelay['array'] = $.isEmptyObject(filterData) ? filterData: SplitScheduleHtml(filterData);
        isLastPack = recordPLCount == parseInt(data['action'].substr(2, 1), 10) && scheduleDelay['array'].length > 1 ? true: false;
        DrawSchedule(scheduleDelay['array'][0], ballType, isLastPack, false);
        if ($('#scheduleTop').add('#scheduleMiddle').add('#scheduleBottom').children('table').length > 0) {
            UnMask();
        }
        scheduleDelay['timer'] = setInterval(function() {
            scheduleDelay['index'] = scheduleDelay['index'] + 1;
            if (scheduleDelay['index'] < scheduleDelay['array'].length) {
                isLastPack = scheduleDelay['array'].length == scheduleDelay['index'] + 1 && recordPLCount == parseInt(data['action'].substr(2, 1), 10) ? true: false;
                DrawSchedule(scheduleDelay['array'][scheduleDelay['index']], ballType, isLastPack, false);
            } else {
                window.clearInterval(scheduleDelay['timer']);
                scheduleDelay['index'] = 0;
                scheduleDelay['array'] = [];
                if (recordPLCount == parseInt(data['action'].substr(2, 1), 10)) {
                    isRecover = true;
                    isLastPack = false;
                    UnMask();
                }
                var json = {
                    'action': data['action'] + '_over',
                    'syn': data['syn']
                };
                FuncInterface.SendCommand(json);
            }
        },
        100);
    } else {
        if (recordPLCount == parseInt(data['action'].substr(2, 1), 10)) {
            var filterData = FilterSchedule(ballType, scheduleData, allianceData, 1);
            DrawSchedule(filterData, ballType, true, true);
            isRecover = true;
            isLastPack = false;
            if ((ballType == 'fv' || ballType == 'sc') && $('#scheduleTop > table').length > 0) {
                $('#scheduleMiddle > table.scTable').addClass('scTop');
            }
            $('#scheduleBlock > div > div').scrollTop(viewPosition);
            GameMarked();
            UnMask();
        }
        var json = {
            'action': data['action'] + '_over',
            'syn': data['syn']
        };
        FuncInterface.SendCommand(json);
    }
}
function InitialCache(data) {
    var returnSchedule = {};
    if ($.isEmptyObject(data)) {
        return;
    }
    for (var i = 0; i < data.length; i++) {
        var gameInfo = data[i];
        var gid = gameInfo['pk'];
        var leagueID = gameInfo['aID'];
        if (!allianceData[leagueID]['type']) {
            allianceData[leagueID]['type'] = gameInfo['pk'].split('_')[0];
        }
        if (!allianceData[leagueID]['gidSet']) {
            allianceData[leagueID]['gidSet'] = [];
        }
        if ($.inArray(gid, allianceData[leagueID]['gidSet']) < 0) {
            allianceData[leagueID]['gidSet'].push(gid);
        }
        scheduleData[gid] = gameInfo;
        returnSchedule[gid] = scheduleData[gid];
    }
    return returnSchedule;
}
function SetBallFunc(type) {
    switch (type) {
    case 'bk':
        ballFunc = FuncBasketball;
        break;
    case 'bb':
    case 'tw':
        ballFunc = FuncBaseball;
        break;
    case 'af':
        ballFunc = FuncAmericaFootball;
        break;
    case 'ih':
        ballFunc = FuncIceHockey;
        break;
    case 'sc':
        ballFunc = FuncSoccer;
        break;
    case 'tn':
        ballFunc = FuncTennis;
        break;
    case 'vl':
    case 'bv':
        ballFunc = FuncVolleyball;
        break;
    case 'hb':
        ballFunc = FuncHandball;
        break;
    case 'es':
        ballFunc = FuncESport;
        break;
    case 'bm':
        ballFunc = FuncBadminton;
        break;
    }
}
function DrawMenuList(data, defaultType) {
    if (data == 'menuDetailModify') {
        var menuDetailArray = [0, 0, 0, 0];
        var targetSelector = '#btn' + defaultType.toUpperCase() + ' > span.menuCount';
        $.each(scheduleData,
        function(gid) {
            menuDetailArray[0]++;
            switch (scheduleData[gid]['gst']) {
            case 'S':
                menuDetailArray[1]++;
                break;
            case 'X':
                menuDetailArray[2]++;
                break;
            case 'E':
                menuDetailArray[3]++;
                break;
            }
        });
        $('#btn' + defaultType.toUpperCase() + ' > span.menuCount').text(menuDetailArray[0]);
        $('#' + defaultType + '_All').text(menuDetailArray[0]);
        $('#' + defaultType + '_S').text(menuDetailArray[1]);
        $('#' + defaultType + '_X').text(menuDetailArray[2]);
        $('#' + defaultType + '_E').text(menuDetailArray[3]);
    } else if (data) {
        if (langFont['Font_Langue'] == 'en') {
            $('#menuList').addClass('menuListEN');
        }
        var keyName = '';
        var htmlResult = '<div><ul>';
        htmlResult += '<li><div id="btnFV" class="menuListBtn" onclick="ChangeType(\'fv\')">';
        htmlResult += '<img src="/images/sport/ic_fv.png" />';
        htmlResult += '<span>' + langFont['Font_MyGame'] + '</span><span class="menuCount">' + FuncFavorite.ScheduleFVGroup['pk'].length + '</span>';
        if (defaultType == 'fv') {
            var menuDetailArray = [0, 0, 0, 0];
            $.each(scheduleData,
            function(gid) {
                menuDetailArray[0]++;
                switch (scheduleData[gid]['gst']) {
                case 'S':
                    menuDetailArray[1]++;
                    break;
                case 'X':
                    menuDetailArray[2]++;
                    break;
                case 'E':
                    menuDetailArray[3]++;
                    break;
                }
            });
            htmlResult += '</div><div class="showStatus" style="display: block">';
            htmlResult += '<a onclick="ChangeStatus(this, \'All\')"' + (sortOption['status'] == 'All' ? ' class="onPage"': '') + '><span class="sortStatus"></span>' + langFont['Font_All'] + '<span class="menuCount" id="fv_All">' + menuDetailArray[0] + '</span></a>';
            htmlResult += '<a onclick="ChangeStatus(this, \'S\')"' + (sortOption['status'] == 'S' ? ' class="onPage"': '') + '><span class="sortStatus"></span>' + langFont['Font_Started'] + '<span class="menuCount" id="fv_S">' + menuDetailArray[1] + '</span></a>';
            htmlResult += '<a onclick="ChangeStatus(this, \'X\')"' + (sortOption['status'] == 'X' ? ' class="onPage"': '') + '><span class="sortStatus"></span>' + langFont['Font_NotStarted'] + '<span class="menuCount" id="fv_X">' + menuDetailArray[2] + '</span></a>';
            htmlResult += '<a onclick="ChangeStatus(this, \'E\')"' + (sortOption['status'] == 'E' ? ' class="onPage"': '') + '><span class="sortStatus"></span>' + langFont['Font_Finished'] + '<span class="menuCount" id="fv_E">' + menuDetailArray[3] + '</span></a>';
        } else {
            htmlResult += '</div><div class="showStatus">';
            htmlResult += '<a onclick="ChangeStatus(this, \'All\')"><span class="sortStatus"></span>' + langFont['Font_All'] + '<span class="menuCount" id="fv_All"></span></a>';
            htmlResult += '<a onclick="ChangeStatus(this, \'S\')"><span class="sortStatus"></span>' + langFont['Font_Started'] + '<span class="menuCount" id="fv_S"></span></a>';
            htmlResult += '<a onclick="ChangeStatus(this, \'X\')"><span class="sortStatus"></span>' + langFont['Font_NotStarted'] + '<span class="menuCount" id="fv_X"></span></a>';
            htmlResult += '<a onclick="ChangeStatus(this, \'E\')"><span class="sortStatus"></span>' + langFont['Font_Finished'] + '<span class="menuCount" id="fv_E"></span></a>';
        }
        htmlResult += '</div></li>';
        var menuCountArray = [];
        for (var i = 0; i < data.length; i++) {
            keyName = Object.keys(data[i])[0];
            menuCountArray = data[i][keyName].split(',');
            htmlResult += '<li><div id="btn' + keyName.toUpperCase() + '" class="menuListBtn" onclick="ChangeType(\'' + keyName + '\')">';
            if (keyName == 'tw') {
                htmlResult += '<img src="/images/sport/ic_bb.png" />';
            } else if (keyName == 'bv') {
                htmlResult += '<img src="/images/sport/ic_vl.png" />';
            } else {
                htmlResult += '<img src="/images/sport/ic_' + keyName + '.png" />';
            }
            htmlResult += '<span>' + TransformGameType(keyName) + '</span><span class="menuCount">' + menuCountArray[0] + '</span>';
            if (keyName == defaultType) {
                htmlResult += '</div><div class="showStatus" style="display: block">';
            } else {
                htmlResult += '</div><div class="showStatus">';
            }
            if (nowDate['string'] == gameDate['string']) {
                htmlResult += '<a onclick="ChangeStatus(this, \'All\')"' + (sortOption['status'] == 'All' ? ' class="onPage"': '') + '><span class="sortStatus"></span>' + langFont['Font_All'] + '<span class="menuCount" id="' + keyName + '_All">' + menuCountArray[0] + '</span></a>';
                htmlResult += '<a onclick="ChangeStatus(this, \'S\')"' + (sortOption['status'] == 'S' ? ' class="onPage"': '') + '><span class="sortStatus"></span>' + langFont['Font_Started'] + '<span class="menuCount" id="' + keyName + '_S">' + menuCountArray[1] + '</span></a>';
                htmlResult += '<a onclick="ChangeStatus(this, \'X\')"' + (sortOption['status'] == 'X' ? ' class="onPage"': '') + '><span class="sortStatus"></span>' + langFont['Font_NotStarted'] + '<span class="menuCount" id="' + keyName + '_X">' + menuCountArray[2] + '</span></a>';
                htmlResult += '<a onclick="ChangeStatus(this, \'E\')"' + (sortOption['status'] == 'E' ? ' class="onPage"': '') + '><span class="sortStatus"></span>' + langFont['Font_Finished'] + '<span class="menuCount" id="' + keyName + '_E">' + menuCountArray[3] + '</span></a>';
            } else {
                htmlResult += '<a onclick="ChangeStatus(this, \'All\')"' + (sortOption['status'] == 'All' ? ' class="onPage"': '') + '><span class="sortStatus"></span>' + langFont['Font_All'] + '</a>';
                htmlResult += '<a onclick="ChangeStatus(this, \'S\')"' + (sortOption['status'] == 'S' ? ' class="onPage"': '') + '><span class="sortStatus"></span>' + langFont['Font_Started'] + '</a>';
                htmlResult += '<a onclick="ChangeStatus(this, \'X\')"' + (sortOption['status'] == 'X' ? ' class="onPage"': '') + '><span class="sortStatus"></span>' + langFont['Font_NotStarted'] + '</a>';
                htmlResult += '<a onclick="ChangeStatus(this, \'E\')"' + (sortOption['status'] == 'E' ? ' class="onPage"': '') + '><span class="sortStatus"></span>' + langFont['Font_Finished'] + '</a>';
            }
            htmlResult += '</div></li>';
        }
        htmlResult += '</ul></div>';
        $('#menuList').html(htmlResult);
    }
}
function TransformGameType(value) {
    switch (value) {
    case 'bb':
        return langFont['Font_Baseball'];
        break;
    case 'tw':
        return langFont['Font_BaseballTW'];
        break;
    case 'bk':
        return langFont['Font_Basketball'];
        break;
    case 'af':
        return langFont['Font_USFootball'];
        break;
    case 'ih':
        return langFont['Font_IceHockey'];
        break;
    case 'tn':
        return langFont['Font_Tennis'];
        break;
    case 'sc':
        return langFont['Font_Soccer'];
        break;
    case 'vl':
        return langFont['Font_Volleyball'];
        break;
    case 'bv':
        return langFont['Font_BeachVolleyball'];
        break;
    case 'hb':
        return langFont['Font_Handball'];
        break;
    case 'es':
        return langFont['Font_ESports'];
        break;
    case 'bm':
        return langFont['Font_Badminton'];
        break;
    }
}
function SetDateOption(dataCount) {
    if (dataCount) {
        var htmlResult = '';
        var tempDate = new Date();
        tempDate.setDate(tempDate.getDate() - 8);
        var monthStr = '';
        var dayStr = '';
        var dateStr = '';
        var dateKey = '';
        var displayStr = '';
        var result = '';
        var prevDay = '';
        var nextDay = '';
        for (var i = 0; i < 15; i++) {
            tempDate.setDate(tempDate.getDate() + 1);
            monthStr = tempDate.getMonth() + 1;
            monthStr = monthStr < 10 ? "0" + monthStr: monthStr;
            dayStr = tempDate.getDate() < 10 ? "0" + tempDate.getDate() : tempDate.getDate();
            dateStr = tempDate.getFullYear() + '/' + monthStr + '/' + dayStr;
            displayStr = monthStr + ' / ' + dayStr;
            dateKey = tempDate.getFullYear() + '' + monthStr + dayStr;
            if (dateStr == gameDate['string']) {
                if (dataCount[dateKey]) {
                    htmlResult += '<a onclick="ChooseDate(this)" class="btnToday" rel="' + dateStr + '" name="' + dateKey + '"><span class="leftDate">' + (dateStr == nowDate['string'] ? langFont['Font_Today'] : displayStr) + ' (' + langFont['Font_WeekDay'][tempDate.getDay()] + ')</span><span class="rightDate">' + dataCount[dateKey] + '</span></a>';
                    $('#gameCount').text(dataCount[dateKey]);
                } else {
                    htmlResult += '<a onclick="ChooseDate(this)" class="btnToday" rel="' + dateStr + '" name="' + dateKey + '"><span class="leftDate">' + (dateStr == nowDate['string'] ? langFont['Font_Today'] : displayStr) + ' (' + langFont['Font_WeekDay'][tempDate.getDay()] + ')</span><span class="rightDate">0</span></a>';
                    $('#gameCount').text(0);
                }
                $('#displayDate').text(displayStr + ' (' + langFont['Font_WeekDay'][tempDate.getDay()] + ')');
            } else {
                if (dataCount[dateKey]) {
                    htmlResult += '<a onclick="ChooseDate(this)" rel="' + dateStr + '" name="' + dateKey + '"><span class="leftDate">' + (dateStr == nowDate['string'] ? langFont['Font_Today'] : displayStr) + ' (' + langFont['Font_WeekDay'][tempDate.getDay()] + ')</span><span class="rightDate">' + dataCount[dateKey] + '</span></a>';
                } else {
                    htmlResult += '<a onclick="ChooseDate(this)" rel="' + dateStr + '" name="' + dateKey + '"><span class="leftDate">' + (dateStr == nowDate['string'] ? langFont['Font_Today'] : displayStr) + ' (' + langFont['Font_WeekDay'][tempDate.getDay()] + ')</span><span class="rightDate">0</span></a>';
                }
            }
        }
        $('#dateOption').html(htmlResult);
        prevDay = $('#dateOption > a.btnToday').prev('a').attr('rel');
        nextDay = $('#dateOption > a.btnToday').next('a').attr('rel');
        if (prevDay) {
            $('#prevDay').attr('onclick', 'ChooseDate(this)').attr('rel', prevDay).removeClass('noDate');
        } else {
            $('#prevDay').removeAttr('onclick').removeAttr('rel').addClass('noDate');
        }
        if (nextDay) {
            $('#nextDay').attr('onclick', 'ChooseDate(this)').attr('rel', nextDay).removeClass('noDate');
        } else {
            $('#nextDay').removeAttr('onclick').removeAttr('rel').addClass('noDate');
        }
    }
}
function ChooseDate(e) {
    if (e.rel != gameDate['string']) {
        ChangeDate($(e).attr('rel'), 0);
    }
}
function ChangeType(value) {
    Mask();
    $.each(scheduleData,
    function(gt) {
        scheduleData[gt] = [];
    });
    $('#scheduleTop').add('#scheduleMiddle').add('#scheduleBottom').empty();
    $('#scheduleNoData').hide();
    leagueArray = {
        'withSID': [],
        'withoutSID': []
    };
    ballType = value;
    isRecover = false;
    $('#scheduleRemind').addClass('hidden');
    if (ballType != 'sc') {
        $('#fixedTitle').hide();
        delete updateItem['#goalMsg'];
    } else {
        updateItem['#goalMsg'] = {
            'time': null,
            'prompt': []
        };
    }
    $('#btnFV').removeClass('onPage');
    if (ballType == 'fv') {
        $('#btnAddFV').addClass('hidden');
        $('#btnRemoveFV').removeClass('hidden');
        $('#menuList li > div > a.onPage').parent().hide();
        $('#menuList li > div > a.onPage').removeClass('onPage');
        $('#btnFV').siblings('.showStatus').show();
        $('#btnFV').siblings('.showStatus').children().eq(0).addClass('onPage');
    } else {
        $('#btnAddFV').removeClass('hidden');
        $('#btnRemoveFV').addClass('hidden');
    }
    sortOption['status'] = 'All';
    soccerCards = {
        "yellowCard": 1,
        "stadings": 1,
        "corner": 1,
        "announces": 1
    };
    $('#ckbYellowCard').addClass('ckbOK');
    $('#ckbStadings').addClass('ckbOK');
    $('#ckbCorner').addClass('ckbOK');
    $('#ckbAnnounces').addClass('ckbOK');
    $('#ddlOrderBy > ul > li').removeClass('onPage');
    sortOption['orderBy'] = orderByForChangeType[ballType];
    var orderByString = sortOption['orderBy'] == 1 ? [langFont['Font_OrderTime'], 'last-child'] : [langFont['Font_OrderLeague'], 'first-child'];
    $('#ddlOrderBy > span').html(orderByString[0] + '<img src="/images/sport/ic_arrowB_white.png" />');
    $('#ddlOrderBy > ul > li:' + orderByString[1]).addClass('onPage');
    ToTop();
    gameDate = $.extend({},
    nowDate);
    var json = {
        'action': 'ct',
        'type': ballType,
        'date': gameDate['string'].replaceAll('/', ''),
        'order': sortOption['orderBy']
    };
    FuncInterface.SendCommand(json);
    recentCommand = json;
}
function FilterSchedule(type, gameData, leagueData, concatType) {
    var resultLeague = [];
    var resultData = {};
    var targetLeagueArray = [];
    if (ballType != 'fv' && sortOption['orderBy'] == 0) {
        targetLeagueArray = leagueArray['withSID'];
    } else {
        targetLeagueArray = leagueArray['withoutSID'];
    }
    if ($.inArray('All', sortOption['league']) >= 0) {
        resultLeague = targetLeagueArray;
    } else {
        resultLeague = targetLeagueArray.filter(function(leagueID) {
            if (leagueData[leagueID]) {
                return $.inArray(leagueID, sortOption['league']) >= 0;
            }
        });
    }
    resultLeague = resultLeague.map(function(leagueID) {
        return $.extend({},
        leagueData[leagueID]);
    });
    for (var i = 0; i < resultLeague.length; i++) {
        if (resultLeague[i]['gidSet']) {
            resultLeague[i]['gidSet'] = resultLeague[i]['gidSet'].filter(function(gid) {
                if (gameData[gid]) {
                    var gameInfo = gameData[gid];
                    return (gameInfo['gst'] == sortOption['status'] || sortOption['status'] == 'All') && $.inArray(gameInfo['pk'], gameMarked['inExclude']) < 0 && ((gameMarked['inKeep'].length > 0 && gameMarked['isKeep'] && $.inArray(gameInfo['pk'], gameMarked['inKeep']) >= 0) || gameMarked['inKeep'].length == 0 && !gameMarked['isKeep']);
                }
            });
        }
    }
    resultLeague = resultLeague.filter(function(league) {
        return league['gidSet'] && league['gidSet'].length > 0;
    });
    if (ballType != 'fv') {
        resultData['S'] = [];
        resultData['E'] = [];
        resultData['top'] = [];
        for (var i = 0; i < resultLeague.length; i++) {
            resultData['S'] = resultData['S'].concat(resultLeague[i]['gidSet'].filter(function(gid) {
                return 'SX'.indexOf(gameData[gid]['gst']) >= 0 && $.inArray(gid, gameMarked['inTop']) < 0;
            }));
            resultData['E'] = resultData['E'].concat(resultLeague[i]['gidSet'].filter(function(gid) {
                return gameData[gid]['gst'] == 'E' && $.inArray(gid, gameMarked['inTop']) < 0;
            }));
            resultData['top'] = resultData['top'].concat(resultLeague[i]['gidSet'].filter(function(gid) {
                return $.inArray(gid, gameMarked['inTop']) >= 0;
            }));
        }
    } else {
        resultData['S'] = [];
        resultData['top'] = [];
        for (var i = 0; i < resultLeague.length; i++) {
            resultData['S'] = resultData['S'].concat(resultLeague[i]['gidSet'].filter(function(gid) {
                return $.inArray(gid, gameMarked['inTop']) < 0;
            }));
            resultData['top'] = resultData['top'].concat(resultLeague[i]['gidSet'].filter(function(gid) {
                return $.inArray(gid, gameMarked['inTop']) >= 0;
            }));
        }
    }
    if (type == 'sc' && resultData['E'] && resultData['E'].length > 0) {
        resultData['S'] = resultData['S'].concat(resultData['E']);
        delete resultData['E'];
    }
    if (ballType != 'fv' && sortOption['orderBy'] == 1) {
        $.each(resultData,
        function(gt) {
            resultData[gt] = $.extend([], resultData[gt]).sort(function(a, b) {
                if (type == 'sc' && gameData[a]['gs'] != gameData[b]['gs']) {
                    var allSates = [langFont['Font_Processing'], langFont['Font_SoccerDown'], langFont['Font_SoccerMiddle'], langFont['Font_SoccerUp'], langFont['Font_NotStarted'], langFont['Font_SoccerOver'], langFont['Font_Undecided'], langFont['Font_InterruSC'], langFont['Font_PostpZuQiu'], langFont['Font_Abandoned'], langFont['Font_CancZuQiu']];
                    return $.inArray(gameData[a]['gs'], allSates) > $.inArray(gameData[b]['gs'], allSates) ? 1 : -1;
                } else if (gameData[a]['gd'] != gameData[b]['gd']) {
                    return gameData[a]['gd'] > gameData[b]['gd'] ? 1 : -1;
                } else if (gameData[a]['gst'] != gameData[b]['gst'] && type != 'sc') {
                    return $.inArray(gameData[a]['gst'], ['S', 'X']) > $.inArray(gameData[b]['gst'], ['S', 'X']) ? 1 : -1;
                } else {
                    return $.inArray(a, resultData[gt]) > $.inArray(b, resultData[gt]) ? 1 : -1;
                }
            });
        });
    } else if (ballType == 'fv') {
        var finishStates = [langFont['Font_Finished'], langFont['Font_SoccerOver'], langFont['Font_FinishedRetired'], langFont['Font_Retired'], langFont['Font_Walkover'], langFont['Font_Abandoned'], langFont['Font_PostpZuQiu'], langFont['Font_Suspended'], langFont['Font_CancZuQiu']];
        $.each(resultData,
        function(gt) {
            resultData[gt] = $.extend([], resultData[gt]).sort(function(a, b) {
                if (type == 'sc' && gameData[a]['gs'] != gameData[b]['gs']) {
                    var allSates = [langFont['Font_Processing'], langFont['Font_SoccerDown'], langFont['Font_SoccerMiddle'], langFont['Font_SoccerUp'], langFont['Font_NotStarted'], langFont['Font_SoccerOver'], langFont['Font_Undecided'], langFont['Font_InterruSC'], langFont['Font_PostpZuQiu'], langFont['Font_Abandoned'], langFont['Font_CancZuQiu']];
                    return $.inArray(gameData[a]['gs'], allSates) > $.inArray(gameData[b]['gs'], allSates) ? 1 : -1;
                } else if (gameData[a]['gst'] != gameData[b]['gst'] && type != 'sc') {
                    return $.inArray(gameData[a]['gst'], ['S', 'X', 'E']) > $.inArray(gameData[b]['gst'], ['S', 'X', 'E']) ? 1 : -1;
                } else if (gameData[a]['gst'] == 'E') {
                    if (gameData[a]['gs'] != gameData[b]['gs']) {
                        return $.inArray(gameData[a]['gs'], finishStates) > $.inArray(gameData[b]['gs'], finishStates) ? 1 : -1;
                    } else if (gameData[a]['gd'] != gameData[b]['gd']) {
                        return gameData[a]['gd'] > gameData[b]['gd'] ? 1 : -1;
                    } else {
                        return $.inArray(a, resultData[gt]) > $.inArray(b, resultData[gt]) ? 1 : -1;
                    }
                } else {
                    if (gameData[a]['gd'] != gameData[b]['gd']) {
                        return gameData[a]['gd'] > gameData[b]['gd'] ? 1 : -1;
                    } else {
                        return $.inArray(a, resultData[gt]) > $.inArray(b, resultData[gt]) ? 1 : -1;
                    }
                }
            });
        });
    }
    if (concatType == 1 || concatType == 3) {
        scheduleArray = $.extend({},
        resultData);
    } else if (concatType == 2 || concatType == 4) {
        $.each(resultData,
        function(gt) {
            if (scheduleArray[gt]) {
                scheduleArray[gt] = scheduleArray[gt].concat(resultData[gt]);
            } else {
                scheduleArray[gt] = $.extend([], resultData[gt]);
            }
        });
    }
    if (concatType == 3 || concatType == 4) {
        return;
    }
    if (type == 'sc') {
        resultData['S'] = resultData['S'].map(function(gid) {
            return $.extend({},
            gameData[gid]);
        });
        resultData['top'] = resultData['top'].map(function(gid) {
            return $.extend({},
            gameData[gid]);
        });
    } else if (type != 'sc') {
        $.each(resultData,
        function(gt) {
            resultData[gt] = FormatSchedule(resultData[gt]);
        });
    }
    $.each(resultData,
    function(gt) {
        if (resultData[gt].length == 0) {
            delete resultData[gt];
        }
    });
    return resultData;
}
function FormatSchedule(gameSet) {
    var packData = [];
    var pack = {};
    for (var i = 0; i < gameSet.length; i++) {
        var gid = gameSet[i];
        if (!pack['id'] || pack['id'] != scheduleData[gid]['aID']) {
            if (pack['id']) {
                packData.push(pack);
            }
            pack = $.extend({},
            allianceData[scheduleData[gid]['aID']]);
            pack['d'] = [];
        }
        pack['d'].push($.extend({},
        scheduleData[gid]));
    }
    if (pack['id']) {
        packData.push(pack);
    }
    return packData;
}
function SplitScheduleHtml(data) {
    var resultArray = [];
    var tempData = {
        'S': [],
        'E': []
    };
    var count = 0;
    var isOver = false;
    $.each(data,
    function(gt) {
        for (var i = 0; i < data[gt].length; i++) {
            tempData[gt].push(data[gt][i]);
            if (ballType == 'sc') {
                count += 1;
            } else {
                count += data[gt][i]['d'].length;
            }
            if (count >= 100) {
                resultArray.push(tempData);
                count = 0;
                tempData = {
                    'S': [],
                    'E': []
                };
                isOver = true;
            } else {
                isOver = false;
            }
        }
    });
    if (isOver == false) {
        resultArray.push(tempData);
    }
    return resultArray;
}
function DrawSchedule(data, type, isLast, isClear) {
    if ($.isEmptyObject(data) && (recordPLCount == 0 || isClear) && ballType != 'fv') {
        $('#scheduleNoData').show();
        $('#scheduleTop').add('#scheduleMiddle').add('#scheduleBottom').empty();
        viewPosition = 0;
        ToTop();
    } else {
        if ($.isEmptyObject(data)) {
            data = {
                'S': []
            };
        }
        $('#scheduleNoData').hide();
        $('#ddlLeague').show();
        if (ballType != 'fv') {
            $('#ddlOrderBy').show();
        }
        var htmlResult = '';
        var scheduleInfo = '';
        $.each(data,
        function(gt) {
            var appendNode = gt == 'top' ? '#scheduleTop': (gt == 'S' ? '#scheduleMiddle': '#scheduleBottom');
            htmlResult = '';
            if (type == 'sc') {
                if (data[gt].length > 0) {
                    if (isClear == false && $(appendNode + ' > table[gt="sc"]').length > 0) {
                        appendNode = appendNode + ' > table[gt="sc"]';
                        htmlResult += FuncSoccer.DrawTable(data[gt], allianceData, gt, false);
                        $(appendNode).append(htmlResult);
                    } else {
                        if (ballType != 'fv') {
                            $('#fixedTitle').show();
                        }
                        htmlResult += FuncSoccer.DrawTable(data[gt], allianceData, gt, true);
                        if (isClear) {
                            $(appendNode).html(htmlResult);
                            if (gt == 'top') {
                                $('#scheduleMiddle').add('#scheduleBottom').empty();
                            } else if (gt == 'S') {
                                $('#scheduleTop').add('#scheduleBottom').empty();
                            } else {
                                $('#scheduleTop').add('#scheduleMiddle').empty();
                            }
                            isClear = false;
                        } else {
                            $(appendNode).append(htmlResult);
                        }
                    }
                }
            } else {
                for (var i = 0; i < data[gt].length; i++) {
                    var isNewTable = true;
                    scheduleInfo = data[gt][i];
                    SetBallFunc(allianceData[scheduleInfo['id']]['type']);
                    htmlResult = '';
                    if (isClear || $(appendNode + ' > table:last').attr('rel') != scheduleInfo['id']) {
                        if (type == 'bk') {
                            htmlResult += '<table rel="' + scheduleInfo['id'] + '" al="' + scheduleInfo['o'] + '" gt="' + type + '" sort="' + scheduleInfo['s'] + '">';
                        } else {
                            htmlResult += '<table rel="' + scheduleInfo['id'] + '" al="' + scheduleInfo['n'] + '" gt="' + type + '" sort="' + scheduleInfo['s'] + '">';
                        }
                        htmlResult += '<caption>';
                        var regExp = /^(?:([A-Za-z]+):)?(\/{0,3})([0-9.\-A-Za-z]+)(?::(\d+))?(?:\/([^?#]*))?(?:\?([^#]*))?(?:#(.*))?$/;
                        var ballIcon = '';
                        if (ballType == 'fv') {
                            if (type == 'tw') {
                                ballIcon = '<img src="/images/sport/ic_bb.png" class="ballIcon">';
                            } else if (type == 'bv') {
                                ballIcon = '<img src="/images/sport/ic_vl.png" class="ballIcon">';
                            } else {
                                ballIcon = '<img src="/images/sport/ic_' + type + '.png" class="ballIcon">';
                            }
                        }
                        if (scheduleInfo['u'] && regExp.test(scheduleInfo['u']) && type != 'sc') {
                            htmlResult += ballIcon + '<a target="_blank" href="' + scheduleInfo['u'] + '" id="aid_' + scheduleInfo['id'] + '">' + scheduleInfo['n'] + '</a>';
                        } else {
                            htmlResult += ballIcon + '<a target="_blank" id="aid_' + scheduleInfo['id'] + '"  class="noHref">' + scheduleInfo['n'] + '</a>';
                        }
                        htmlResult += '</caption>';
                    } else {
                        isNewTable = false;
                    }
                    var count = 1;
                    for (var j = 0; j < scheduleInfo['d'].length; j++) {
                        var showTitle = (count == 1 && isNewTable) ? '': 'hidden';
                        htmlResult += ballFunc.AddGameData((scheduleInfo['o'] ? scheduleInfo['o'] : ''), scheduleInfo['d'][j], count, showTitle, false);
                        count++;
                    }
                    if (isNewTable == true) {
                        htmlResult += '</table>';
                        if (isClear) {
                            $(appendNode).html(htmlResult);
                            if (gt == 'top') {
                                $('#scheduleMiddle').add('#scheduleBottom').empty();
                            } else if (gt == 'S') {
                                $('#scheduleTop').add('#scheduleBottom').empty();
                            } else {
                                $('#scheduleTop').add('#scheduleMiddle').empty();
                            }
                            isClear = false;
                        } else {
                            $(appendNode).append(htmlResult);
                        }
                    } else {
                        $(appendNode + ' > table:last').append(htmlResult);
                    }
                }
            }
        });
        if (recordPLCount == 0 && ballType != 'fv') {
            var tempTable = $('#scheduleMiddle > table');
            if (tempTable.length > 0 && $(tempTable[0]).attr('gt') != ballType) {
                $('#scheduleMiddle').empty();
            }
            tempTable = $('#scheduleBottom > table');
            if (tempTable.length > 0 && $(tempTable[0]).attr('gt') != ballType) {
                $('#scheduleBottom').empty();
            }
        }
    }
    if (isLast && $('#scheduleMiddle > table:visible').add('#scheduleTop > table:visible').add('#scheduleBottom > table:visible').length == 0) {
        $('#scheduleNoData').show();
        $('#fixedTitle').hide();
    }
}
function GameMarked() {
    for (var i = 0; i < gameMarked['checked'].length; i++) {
        if (!$(gameMarked['checked'][i]).children('td[class="check"]').children('div').hasClass('ckbOK')) {
            ClickScheduleCkb($(gameMarked['checked'][i]).children('td[class="check"]'));
        }
    }
}
function ClickAllianceCkb(e) {
    if ($(e).prop('tagName') == 'TH') {
        e = $(e).children('div');
    }
    var scrollTop = $('#scheduleBlock > div > div').scrollTop();
    var topHeight = $('#scheduleTop').css('height').split('px')[0];
    if ($(e).hasClass('ckbOK')) {
        $(e).removeClass('ckbOK');
        $(e).parents('tbody').find('tr[class^="mainRow"]:visible > td[class="check"] > div').removeClass('ckbOK');
        $(e).parents('tbody').find('tr[class^="mainRow"]:visible').each(function() {
            gameMarked['checked'].remove('#' + $(this).attr('id'));
        });
    } else {
        $(e).addClass('ckbOK');
        $(e).parents('tbody').find('tr[class^="mainRow"]:visible > td[class="check"] > div').addClass('ckbOK');
        $(e).parents('tbody').find('tr[class^="mainRow"]:visible').each(function() {
            if ($.inArray('#' + $(this).attr('id'), gameMarked['checked']) < 0) {
                gameMarked['checked'].push('#' + $(this).attr('id'));
            }
        });
    }
}
function ClickAllianceCkbSC(e) {
    var scrollTop = $('#scheduleBlock > div > div').scrollTop();
    var topHeight = $('#scheduleTop').css('height').split('px')[0];
    var changeBlock = scrollTop < topHeight ? '#scheduleTop': '#scheduleMiddle';
    if ($(e).hasClass('ckbOK')) {
        $(e).removeClass('ckbOK');
        $(changeBlock + ' #sc_thRow > th[class="check"] > div').removeClass('ckbOK');
        $(changeBlock + ' > .scTable > tbody > tr[class^="mainRow"]:visible > td[class="check"] > div').removeClass('ckbOK');
        $(changeBlock + ' > .scTable > tbody > tr[class^="mainRow"]:visible').each(function() {
            gameMarked['checked'].remove('#' + $(this).attr('id'));
        });
    } else {
        $(e).addClass('ckbOK');
        $(changeBlock + ' #sc_thRow > th[class="check"] > div').addClass('ckbOK');
        $(changeBlock + ' > .scTable > tbody > tr[class^="mainRow"]:visible > td[class="check"] > div').addClass('ckbOK');
        $(changeBlock + ' > .scTable > tbody > tr[class^="mainRow"]:visible').each(function() {
            if ($.inArray('#' + $(this).attr('id'), gameMarked['checked']) < 0) {
                gameMarked['checked'].push('#' + $(this).attr('id'));
            }
        });
    }
}
function ClickScheduleCkb(e) {
    e = $(e).children('div');
    if ($(e).hasClass('ckbOK')) {
        $(e).removeClass('ckbOK');
        gameMarked['checked'].remove('#' + $(e).parents('tr').attr('id'));
    } else {
        $(e).addClass('ckbOK');
        if ($.inArray('#' + $(e).parents('tr').attr('id'), gameMarked['checked']) < 0) {
            gameMarked['checked'].push('#' + $(e).parents('tr').attr('id'));
        }
    }
    var tableElement = $(e).parents('table');
    var checks = tableElement.find('tr.mainRow:visible > td.check');
    var trAllCount = checks.length;
    var trOKCount = checks.find('.ckbOK').length;
    var scheduleScroll = $('#scheduleBlock > div > div').scrollTop();
    var topHeight = $('#scheduleTop').css('height').split('px')[0];
    if (trAllCount == trOKCount) {
        if (tableElement.attr('gt') == 'sc') {
            tableElement.find('#sc_thRow > th[class="check"] > div').addClass('ckbOK');
            if (scheduleScroll < topHeight) {
                if (tableElement.parents('div').attr('id') == 'scheduleTop') {
                    $('#fixedTitle > span.check > span.ckb').addClass('ckbOK');
                }
            } else {
                $('#fixedTitle > span.check > span.ckb').addClass('ckbOK');
            }
        } else {
            tableElement.find('tr[id$="headerRow"]:visible > th.check > div').addClass('ckbOK');
        }
    } else {
        if (tableElement.attr('gt') == 'sc') {
            tableElement.find('#sc_thRow > th[class="check"] > div').removeClass('ckbOK');
            if (scheduleScroll < topHeight) {
                if (tableElement.parents('div').attr('id') == 'scheduleTop') {
                    $('#fixedTitle > span.check > span.ckb').removeClass('ckbOK');
                }
            } else {
                $('#fixedTitle > span.check > span.ckb').removeClass('ckbOK');
            }
        } else {
            tableElement.find('tr[id$="headerRow"]:visible > th.check > div').removeClass('ckbOK');
        }
    }
}
function SetLeagueOption() {
    var htmlText = '';
    var getDate = ballType == 'fv' ? 'fv': ballType + '_' + gameDate['string'].substr(5, 5);
    var getLeagueOption = GetCookie(getDate);
    if (getLeagueOption.length > 0) {
        getLeagueOption = getLeagueOption.split(',').sort(function(a, b) {
            if ($.inArray(a, leagueArray['withoutSID']) != $.inArray(b, leagueArray['withoutSID'])) {
                return ($.inArray(a, leagueArray['withoutSID']) > $.inArray(b, leagueArray['withoutSID'])) ? 1 : -1;
            }
        });
    }
    var array = leagueArray['withoutSID'].filter(function(leagueID) {
        return $.inArray(leagueID, getLeagueOption) < 0;
    });
    array = (getLeagueOption.length > 0 ? getLeagueOption: []).concat(array);
    var isAll = false;
    if ($.inArray('All', array) >= 0 || $.inArray('All', sortOption['league']) >= 0) {
        $('#allLeague > label > span.ckb').addClass('ckbOK');
        array.remove('All');
        isAll = true;
    }
    var itemClass = 'optionItem';
    if (navigator.userAgent.toLocaleLowerCase().indexOf('mobile') < 0 && navigator.userAgent.toLocaleLowerCase().indexOf('android') < 0) {
        itemClass = itemClass + ' pcHover';
    } else {
        $('#allLeague > .pcHover').removeClass('pcHover');
    }
    var okCount = 0;
    var delLeague = [];
    var amount = Math.ceil(leagueArray['withoutSID'].length / 2);
    htmlText += '<div>';
    for (var i = 0; i < amount; i++) {
        if (allianceData[array[i]]) {
            var setCbk = "ckb";
            if (isAll || $.inArray(array[i], sortOption['league']) >= 0 || $.inArray(array[i], getLeagueOption) >= 0) {
                setCbk = "ckb ckbOK";
                okCount++;
            }
            htmlText += '<label class="' + itemClass + '" rel="' + array[i] + '" onclick="ClickLeagueCkb(this)">';
            htmlText += '<span class="' + setCbk + '"></span>';
            if (ballType == 'fv') {
                if (allianceData[array[i]]['type'] == 'tw') {
                    htmlText += '<span class="bbIcon"></span>';
                } else if (allianceData[array[i]]['type'] == 'bv') {
                    htmlText += '<span class="vlIcon"></span>';
                } else {
                    htmlText += '<span class="' + allianceData[array[i]]['type'] + 'Icon"></span>';
                }
            }
            htmlText += '<span class="ckbText">' + allianceData[array[i]]['n'] + '</span>';
            htmlText += '</label>';
        } else {
            delLeague.push(array[i]);
        }
    }
    htmlText += '</div><div>';
    for (var i = amount; i < array.length; i++) {
        if (allianceData[array[i]]) {
            var setCbk = "ckb";
            if (isAll || $.inArray(array[i], sortOption['league']) >= 0 || $.inArray(array[i], getLeagueOption) >= 0) {
                setCbk = "ckb ckbOK";
                okCount++;
            }
            htmlText += '<label class="' + itemClass + '" rel="' + array[i] + '" onclick="ClickLeagueCkb(this)">';
            htmlText += '<span class="' + setCbk + '"></span>';
            if (ballType == 'fv') {
                if (allianceData[array[i]]['type'] == 'tw') {
                    htmlText += '<span class="bbIcon"></span>';
                } else if (allianceData[array[i]]['type'] == 'bv') {
                    htmlText += '<span class="vlIcon"></span>';
                } else {
                    htmlText += '<span class="' + allianceData[array[i]]['type'] + 'Icon"></span>';
                }
            }
            htmlText += '<span class="ckbText">' + allianceData[array[i]]['n'] + '</span>';
            htmlText += '</label>';
        } else {
            delLeague.push(array[i]);
        }
    }
    htmlText += '</div>';
    sortOption['league'] = getLeagueOption;
    for (var i = 0; i < delLeague.length; i++) {
        sortOption['league'].remove(delLeague[i]);
    }
    var getDate = ballType == 'fv' ? 'fv': ballType + '_' + gameDate['string'].substr(5, 5);
    sortOption['league'] = sortOption['league'].length == 0 ? ['All'] : sortOption['league'];
    SetCookie(getDate, sortOption['league']);
    if (leagueArray['withoutSID'].length == okCount) {
        $('#allLeague > label > span.ckb').addClass('ckbOK');
    } else {
        $('#allLeague > label > span.ckb').removeClass('ckbOK');
    }
    $('#otherLeague').scrollbar('destroy');
    $('#otherLeague').html(htmlText);
    $('#otherLeague').scrollTop(0);
    if (sortOption['league'] == 'All') {
        $('#ddlLeague > div').removeClass('ckbLeague');
    } else {
        $('#ddlLeague > div').addClass('ckbLeague');
    }
    var firstblock = $('#otherLeague > div:first').children('label').children('.ckbText');
    var secondblock = $('#otherLeague > div:last').children('label').children('.ckbText');
    for (var i = 0; i < firstblock.length; i++) {
        if ($(firstblock[i]).parent().height() >= $(firstblock[i]).height() - 10 && $(secondblock[i]).length > 0 && $(secondblock[i]).parent().height() >= $(secondblock[i]).height() - 10) {
            continue;
        } else {
            var height = $(secondblock[i]).length > 0 && $(firstblock[i]).height() < $(secondblock[i]).height() ? $(secondblock[i]).height() : $(firstblock[i]).height();
            $($(firstblock[i])).parent().height(height);
            if ($(secondblock[i]).length > 0) {
                $($(secondblock[i])).parent().height(height);
            }
        }
    }
    var totalHeight = 5;
    for (var i = 0; i < (firstblock.length < 9 ? firstblock.length: 9); i++) {
        var e = $($(firstblock)[i]);
        if (e.length > 0) {
            totalHeight += e.parent().height() + 10;
        }
    }
    $('#otherLeague > div').css("height", totalHeight);
    $("#otherLeague").scrollbar({
        'disableBodyScroll': true
    });
}
function ClickLeagueCkb(e) {
    e = $(e).children('span.ckb');
    if ($(e).hasClass('ckbOK')) {
        $(e).removeClass('ckbOK');
    } else {
        $(e).addClass('ckbOK');
    }
    var allCount = $('#otherLeague > div > label > span.ckb').length;
    var okCount = $('#otherLeague > div > label > span.ckbOK').length;
    if (allCount == okCount) {
        $('#allLeague > label > span.ckb').addClass('ckbOK');
    } else {
        $('#allLeague > label > span.ckb').removeClass('ckbOK');
    }
}
function ClickAllLeagueCkb(e) {
    e = $(e).children('span.ckb');
    if ($(e).hasClass('ckbOK')) {
        $(e).removeClass('ckbOK');
        $('#otherLeague > div > label > span.ckb').removeClass('ckbOK');
    } else {
        $(e).addClass('ckbOK');
        $('#otherLeague > div > label > span.ckb').addClass('ckbOK');
    }
}
function LeagueSubmit() {
    var leagueSet = [];
    if ($('#allLeague > label > span.ckbOK').length > 0 || $('#otherLeague > div > label > span.ckbOK').length == 0) {
        leagueSet = ['All'];
    } else {
        $('#otherLeague > div > label > span.ckbOK').each(function() {
            leagueSet.push($(this).parent().attr('rel'));
        });
    }
    var getDate = ballType == 'fv' ? 'fv': ballType + '_' + gameDate['string'].substr(5, 5);
    SetCookie(getDate, leagueSet);
    ChangeLeague(leagueSet);
    $('#leagueOption').offset({
        top: -500,
        left: -500
    });
    $('#boundary').show();
    SetLeagueOption();
    $('#boundary').hide();
    $('#leagueOption').removeAttr('style');
    $('html').removeClass('noScroll');
}
function ShowLeagueOption() {
    if ($('#boundary:visible').length > 0) {
        $('#otherLeague').scrollbar('destroy');
        $('#otherLeague').scrollTop(0);
        var firstblock = $('#otherLeague > div:first').children('label').children('.ckbText');
        var totalHeight = 5;
        for (var i = 0; i < (firstblock.length < 9 ? firstblock.length: 9); i++) {
            var e = $($(firstblock)[i]);
            if (e.length > 0) {
                totalHeight += e.parent().height() + 10;
            }
        }
        $('#otherLeague > div').css("height", totalHeight);
        $("#otherLeague").scrollbar({
            'disableBodyScroll': true
        });
        $('html').removeClass('noScroll');
        $('#boundary').hide();
    } else {
        if ($.inArray('All', sortOption['league']) < 0 && sortOption['league'].length > 0) {
            $('#allLeague > label > span.ckbOK').removeClass('ckbOK');
            $('#otherLeague > div > label > span.ckb').each(function() {
                if ($.inArray($(this).parent().attr('rel'), sortOption['league']) >= 0) {
                    $(this).addClass('ckbOK');
                } else {
                    $(this).removeClass('ckbOK');
                }
            });
        } else {
            $('#allLeague > label > span.ckb').addClass('ckbOK');
            $('#otherLeague > div > label > span.ckb').addClass('ckbOK');
        }
        $('html').addClass('noScroll');
        $('#boundary').show();
        var divHeight = $('#leagueOption').height();
        var divWidth = $('#leagueOption').width();
        var scrollX = window.pageXOffset;
        var windowHeight = $(window).height();
        var windowWidth = $(window).width();
        $('#leagueOption').offset({
            top: (divHeight >= windowHeight ? 0 : (windowHeight - divHeight > 230 ? 230 : (windowHeight - divHeight) / 2)),
            left: (divWidth >= windowWidth ? 0 : (windowWidth - divWidth) / 2 + scrollX)
        });
    }
}
function ShowOrHideElement() {
    if (ballType == 'fv') {
        $('#ddlOrderBy').hide();
        $('#ddlLeague').show();
    } else {
        $('#ddlOrderBy').show();
        $('#ddlLeague').show();
    }
    var gameCount = (ballType == 'fv') ? parseInt($('#btnFV > span.menuCount').text(), 10) : parseInt($('#gameCount').text(), 10);
    if (gameCount <= 0 || isNaN(gameCount)) {
        $('#ddlOrderBy').hide();
        $('#ddlLeague').hide();
    }
    if (ballType == 'fv') {
        $('#hideSetting > #chooseDate').hide();
        $('#hideSetting > #prevDay').hide();
        $('#hideSetting > #nextDay').hide();
        $('#btnAddFV').hide();
        $('#btnRemoveFV').show();
        $('#menuList li > div > a.onPage').parent().hide();
        $('#btnFV').siblings('.showStatus').show();
    } else {
        $('#hideSetting > #chooseDate').show();
        $('#hideSetting > #prevDay').show();
        $('#hideSetting > #nextDay').show();
        $('#btnAddFV').show();
        $('#btnRemoveFV').hide();
    }
    if (ballType == 'sc') {
        $('#soccerDisplay').show();
    } else if (ballType == 'fv' && FuncFavorite.ScheduleFVGroup['pk'].join(',').indexOf('sc') >= 0) {
        $('#soccerDisplay').show();
    } else {
        $('#soccerDisplay').hide();
    }
    $('#chooseSort').show();
    if ($('#chooseSort').children(':visible').length == 0) {
        $('#chooseSort').hide();
    } else {
        $('#chooseSort').show();
    }
    $('#dateOption').width($('#chooseDate').outerWidth() + 15);
}
function ChangeStatus(e, value) {
    Mask();
    gameMarked['checked'] = [];
    $('#fixedTitle > span.check > span').removeClass('ckbOK');
    $('#menuList li > div > a.onPage').removeClass('onPage');
    $(e).addClass('onPage');
    sortOption['status'] = value;
    $('#scheduleNoData').hide();
    setTimeout(function() {
        ShowOrHideElement();
        if (ballType == 'fv') {
            FuncFavorite.DrawFavoriteSchedule(scheduleData, allianceData, leagueArray['withoutSID'], true);
        } else {
            var filterData = FilterSchedule(ballType, scheduleData, allianceData, 1);
            DrawSchedule(filterData, ballType, true, true);
        }
        if ((ballType == 'fv' || ballType == 'sc') && $('#scheduleTop > table').length > 0) {
            $('#scheduleMiddle > table.scTable').addClass('scTop');
        }
        ToTop();
        UnMask();
    },
    50);
}
function ShowDateOption() {
    $('#dateOption').toggle();
}
function ShowRouteOption() {
    $('#routeOption').toggle();
}
function ShowLangOption() {
    $('#langOption').toggle();
}
function ShowOrderByOption() {
    $('#orderByOption').toggle();
}
function ChangeDate(date, value) {
    Mask();
    if (date) {
        gameDate['string'] = date;
        gameDate['object'] = new Date(date);
    } else {
        var tempDate = new Date($('#dateOption > a[class="btnToday"]').attr('rel'));
        if (value != undefined && !isNaN(value)) {
            tempDate.setDate(tempDate.getDate() + value);
        }
        var maxDate = new Date();
        maxDate.setDate(new Date().getDate() + 7);
        var minDate = new Date();
        minDate.setDate(new Date().getDate() - 7);
        if (tempDate > maxDate) {
            tempDate = maxDate;
        }
        if (tempDate < minDate) {
            tempDate = minDate;
        }
        var monthStr = tempDate.getMonth() + 1;
        monthStr = monthStr < 10 ? "0" + monthStr: monthStr;
        var dateStr = tempDate.getDate() < 10 ? "0" + tempDate.getDate() : tempDate.getDate();
        gameDate['string'] = tempDate.getFullYear() + '/' + monthStr + '/' + dateStr;
        gameDate['object'] = new Date(gameDate['string']);
        $('#dateOption').children('a').removeClass('btnToday');
        $('#dateOption').children('a[rel="' + gameDate['string'] + '"]').addClass('btnToday');
    }
    leagueArray = {
        'withSID': [],
        'withoutSID': []
    };
    isRecover = false;
    ToTop();
    if (ballType == 'sc') {
        $('#scheduleRemind').addClass('hidden');
    }
    sortOption['status'] = 'All';
    var json = {
        'action': 'ct',
        'type': ballType,
        'date': gameDate['string'].replaceAll('/', ''),
        'order': sortOption['orderBy']
    };
    FuncInterface.SendCommand(json);
    recentCommand = json;
}
function ChangeOrderBy(newSort) {
    Mask();
    gameMarked['checked'] = [];
    $('#fixedTitle > span.check > span').removeClass('ckbOK');
    orderByForChangeType[ballType] = newSort;
    if (sortOption['orderBy'] != newSort) {
        switch (sortOption['orderBy']) {
        case 0:
            sortOption['orderBy'] = newSort;
            $('#ddlOrderBy > span').html(langFont['Font_OrderTime'] + '<img src="/images/sport/ic_arrowB_white.png" />');
            $('#ddlOrderBy > ul > li').removeClass('onPage');
            $('#ddlOrderBy > ul > li:last-child').addClass('onPage');
            break;
        case 1:
            sortOption['orderBy'] = newSort;
            $('#ddlOrderBy > span').html(langFont['Font_OrderLeague'] + '<img src="/images/sport/ic_arrowB_white.png" />');
            $('#ddlOrderBy > ul > li').removeClass('onPage');
            $('#ddlOrderBy > ul > li:first-child').addClass('onPage');
            break;
        default:
            UnMask();
            return;
        }
    } else {
        UnMask();
        return;
    }
    setTimeout(function() {
        ShowOrHideElement();
        var filterData = FilterSchedule(ballType, scheduleData, allianceData, 1);
        DrawSchedule(filterData, ballType, true, true);
        if ((ballType == 'fv' || ballType == 'sc') && $('#scheduleTop > table').length > 0) {
            $('#scheduleMiddle > table.scTable').addClass('scTop');
        }
        ToTop();
        UnMask();
    },
    50);
}
function ChangeLeague(leagueSet) {
    Mask();
    if (leagueSet.length > 0 && sortOption['league'].join('') != leagueSet.join('')) {
        sortOption['league'] = leagueSet;
        gameMarked['inExclude'] = [];
        gameMarked['inKeep'] = [];
        gameMarked['isKeep'] = false;
        setTimeout(function() {
            ShowOrHideElement();
            if (ballType == 'fv') {
                FuncFavorite.DrawFavoriteSchedule(scheduleData, allianceData, leagueArray['withoutSID'], true);
            } else {
                var filterData = FilterSchedule(ballType, scheduleData, allianceData, 1);
                DrawSchedule(filterData, ballType, true, true);
            }
            gameMarked['checked'] = [];
            $('#fixedTitle > span.check > span').removeClass('ckbOK');
            if (sortOption['league'] == 'All') {
                $('#ddlLeague > div').removeClass('ckbLeague');
            } else {
                $('#ddlLeague > div').addClass('ckbLeague');
            }
            if ((ballType == 'fv' || ballType == 'sc') && $('#scheduleTop > table').length > 0) {
                $('#scheduleMiddle > table.scTable').addClass('scTop');
            }
            UnMask();
        },
        50);
    } else {
        UnMask();
    }
}
function SetScheduleToTop() {
    var haveChoose = false;
    var tempGid = '';
    gameMarked['checked'] = [];
    $('#fixedTitle > span.check > span').removeClass('ckbOK');
    $('#scheduleMiddle > table > tbody > tr[class^="mainRow"] > td[class="check"] > div[class$="ckbOK"]').add('#scheduleTop > table > tbody > tr[class^="mainRow"] > td[class="check"] > div[class$="ckbOK"]').add('#scheduleBottom > table > tbody > tr[class^="mainRow"] > td[class="check"] > div[class$="ckbOK"]').each(function() {
        haveChoose = true;
        var tempPK = $(this).parents('tr').attr('gid');
        tempPK = tempPK.indexOf('sc_') == 0 ? tempPK.replace(new RegExp('c$'), '') : tempPK;
        if (tempGid == tempPK) {
            return;
        } else {
            tempGid = tempPK;
        }
        var inTopIndex = $.inArray(tempPK, gameMarked['inTop']);
        if (inTopIndex < 0) {
            gameMarked['inTop'].push(tempPK);
        } else {
            gameMarked['inTop'].splice(inTopIndex, 1);
        }
    });
    if (haveChoose == false) {
        alert(langFont['Font_SelectMatches']);
        return;
    } else {
        Mask();
        setTimeout(function() {
            ShowOrHideElement();
            if (ballType == 'fv') {
                FuncFavorite.DrawFavoriteSchedule(scheduleData, allianceData, leagueArray['withoutSID'], true);
            } else {
                var filterData = FilterSchedule(ballType, scheduleData, allianceData, 1);
                DrawSchedule(filterData, ballType, true, true);
            }
            if ((ballType == 'fv' || ballType == 'sc') && $('#scheduleTop > table').length > 0) {
                $('#scheduleMiddle > table.scTable').addClass('scTop');
            }
            UnMask();
        },
        50);
    }
}
function KeepSchedule() {
    var haveChoose = false;
    gameMarked['checked'] = [];
    gameMarked['inKeep'] = [];
    $('#fixedTitle .check > span').removeClass('ckbOK');
    $('#scheduleMiddle > table > tbody > tr > td[class="check"] > div[class$="ckbOK"]').add('#scheduleTop > table > tbody > tr > td[class="check"] > div[class$="ckbOK"]').add('#scheduleBottom > table > tbody > tr > td[class="check"] > div[class$="ckbOK"]').each(function() {
        haveChoose = true;
        var tempPK = $(this).parents('tr').attr('gid');
        tempPK = tempPK.indexOf('sc_') == 0 ? tempPK.replace(new RegExp('c$'), '') : tempPK;
        if ($.inArray(tempPK, gameMarked['inKeep']) < 0) {
            gameMarked['isKeep'] = true;
            gameMarked['inKeep'].push(tempPK);
        }
    });
    if (haveChoose == false) {
        alert(langFont['Font_SelectMatches']);
        return;
    } else {
        Mask();
        setTimeout(function() {
            ShowOrHideElement();
            if (ballType == 'fv') {
                FuncFavorite.DrawFavoriteSchedule(scheduleData, allianceData, leagueArray['withoutSID'], true);
            } else {
                var filterData = FilterSchedule(ballType, scheduleData, allianceData, 1);
                DrawSchedule(filterData, ballType, true, true);
            }
            if ((ballType == 'fv' || ballType == 'sc') && $('#scheduleTop > table').length > 0) {
                $('#scheduleMiddle > table.scTable').addClass('scTop');
            }
            UnMask();
        },
        50);
    }
}
function ExculdeSchedule() {
    var haveChoose = false;
    gameMarked['checked'] = [];
    $('#fixedTitle > span.check > span').removeClass('ckbOK');
    $('#scheduleMiddle > table > tbody > tr > td[class="check"] > div[class$="ckbOK"]').add('#scheduleTop > table > tbody > tr > td[class="check"] > div[class$="ckbOK"]').add('#scheduleBottom > table > tbody > tr > td[class="check"] > div[class$="ckbOK"]').each(function() {
        haveChoose = true;
        var tempPK = $(this).parents('tr').attr('gid');
        tempPK = tempPK.indexOf('sc_') == 0 ? tempPK.replace(new RegExp('c$'), '') : tempPK;
        if ($.inArray(tempPK, gameMarked['inExclude']) < 0) {
            gameMarked['inExclude'].push(tempPK);
            var keepIndex = $.inArray(tempPK, gameMarked['inKeep']);
            if (keepIndex >= 0) {
                gameMarked['inKeep'].splice(keepIndex, 1);
            }
        }
    });
    if (haveChoose == false) {
        alert(langFont['Font_SelectMatches']);
        return;
    } else {
        Mask();
        setTimeout(function() {
            ShowOrHideElement();
            if (ballType == 'fv') {
                FuncFavorite.DrawFavoriteSchedule(scheduleData, allianceData, leagueArray['withoutSID'], true);
            } else {
                var filterData = FilterSchedule(ballType, scheduleData, allianceData, 1);
                DrawSchedule(filterData, ballType, true, true);
            }
            if ((ballType == 'fv' || ballType == 'sc') && $('#scheduleTop > table').length > 0) {
                $('#scheduleMiddle > table.scTable').addClass('scTop');
            }
            UnMask();
        },
        50);
    }
}
function AddFavoriteSchedule() {
    var haveChoose = false;
    var overChoose = false;
    var array = {};
    var getDate = 'fv';
    var getLeagueOption = GetCookie(getDate).split(',');
    var cookieNum = getLeagueOption.length;
    gameMarked['checked'] = [];
    $('#scheduleMiddle table tr[class^="mainRow"] td[class="check"] div[class$="ckbOK"]').add('#scheduleTop table tr[class^="mainRow"] td[class="check"] div[class$="ckbOK"]').add('#scheduleBottom table tr[class^="mainRow"] td[class="check"] div[class$="ckbOK"]').each(function() {
        haveChoose = true;
        var gid = $(this).parents('tr').attr('gid');
        gid = gid.indexOf('sc_') == 0 ? gid.replace(new RegExp('c$'), '') : gid;
        var fvDate = scheduleData[gid]['gd'].substr(0, 10).replaceAll('-', '');
        if (FuncFavorite.ScheduleFVGroup['pk'].length < 99) {
            if ($.inArray(gid, FuncFavorite.ScheduleFVGroup['pk']) < 0) {
                FuncFavorite.ScheduleFVGroup['pk'].push(gid);
                FuncFavorite.ScheduleFVGroup['date'].push(fvDate);
                array[fvDate] = array[fvDate] ? array[fvDate] : [];
                if ($.inArray(gid, array[fvDate]) < 0) {
                    array[fvDate].push(gid);
                    var aID = scheduleData[gid]['aID'];
                    if (getLeagueOption != '' && getLeagueOption != 'All' && getLeagueOption.indexOf(aID) < 0) {
                        getLeagueOption[cookieNum] = aID;
                        SetCookie(getDate, getLeagueOption);
                        cookieNum++;
                    }
                }
            }
        } else {
            overChoose = true;
        }
        $(this).removeClass('ckbOK');
        SetCookie('fvPK', FuncFavorite.ScheduleFVGroup['pk']);
        SetCookie('fvDate', FuncFavorite.ScheduleFVGroup['date']);
    });
    $('#scheduleMiddle > table > tbody > tr > th[class="check"] > div[class$="ckbOK"]').add('#scheduleTop > table > tbody > tr > th[class="check"] > div[class$="ckbOK"]').add('#sc_thRow > th > div[class$="ckbOK"]').add('#scheduleBottom > table > tbody > tr > th[class="check"] > div[class$="ckbOK"]').each(function() {
        $(this).removeClass('ckbOK');
    });
    $('#fixedTitle > span.check > span').removeClass('ckbOK');
    if (haveChoose == false) {
        alert(langFont['Font_SelectMatches']);
        return;
    }
    $('#btnFV > span.menuCount').text(FuncFavorite.ScheduleFVGroup['pk'].length);
    var json = {
        'action': 'sf',
        'fvPK': array
    };
    FuncInterface.SendCommand(json);
    recentCommand = json;
    if (overChoose == true) {
        alert(langFont['Font_FavoriteOverLimit']);
        return;
    }
}
function RemoveFavoriteSchedule() {
    Mask();
    gameMarked['checked'] = [];
    var array = [];
    $('#scheduleMiddle > table > tbody > tr[class^="mainRow"] > td[class="check"] > div[class$="ckbOK"]').add('#scheduleTop > table > tbody > tr[class^="mainRow"] > td[class="check"] > div[class$="ckbOK"]').add('#scheduleBottom > table > tbody > tr[class^="mainRow"] > td[class="check"] > div[class$="ckbOK"]').each(function() {
        var gid = $(this).parents('tr').attr('gid');
        gid = gid.indexOf('sc_') == 0 ? gid.replace(new RegExp('c$'), '') : gid;
        if ($.inArray(gid, array) < 0) {
            array.push(gid);
        }
    });
    if (array.length == 0) {
        alert(langFont['Font_SelectMatches']);
        UnMask();
        return;
    }
    array.map(function(gid) {
        var favoriteIndex = jQuery.inArray(gid, FuncFavorite.ScheduleFVGroup['pk']);
        FuncFavorite.ScheduleFVGroup['date'].splice(favoriteIndex, 1);
        FuncFavorite.ScheduleFVGroup['pk'].splice(favoriteIndex, 1);
        if ($.inArray(gid, gameMarked['inKeep']) >= 0) {
            gameMarked['inKeep'].remove(gid);
        }
        var leagueID = scheduleData[gid]['aID'];
        allianceData[leagueID]['gidSet'].remove(gid);
        if (allianceData[leagueID]['gidSet'].length == 0) {
            delete allianceData[leagueID];
            leagueArray['withoutSID'].remove(leagueID);
            leagueArray['withSID'].remove(leagueID);
            sortOption['league'].remove(leagueID);
            if (sortOption['league'].length == 0) {
                sortOption['league'] = ['All']
            }
            var getDate = 'fv';
            SetCookie(getDate, sortOption['league']);
        }
        delete scheduleData[gid];
        SetCookie('fvPK', FuncFavorite.ScheduleFVGroup['pk']);
        SetCookie('fvDate', FuncFavorite.ScheduleFVGroup['date']);
        return leagueID;
    });
    gameMarked['isKeep'] = gameMarked['inKeep'].length == 0 ? false: gameMarked['isKeep'];
    DrawMenuList('menuDetailModify', 'fv');
    if (FuncFavorite.ScheduleFVGroup['pk'].length == 0) {
        $('#scheduleNoData').show();
    }
    var json = {
        'action': 'rf',
        'type_gid': array
    };
    FuncInterface.SendCommand(json);
    recentCommand = json;
    $('#scheduleTop').add('#scheduleMiddle').add('#scheduleBottom').empty();
    setTimeout(function() {
        $('#leagueOption').offset({
            top: -500,
            left: -500
        });
        $('#boundary').show();
        SetLeagueOption();
        $('#boundary').hide();
        $('#leagueOption').removeAttr('style');
        ShowOrHideElement();
        FuncFavorite.DrawFavoriteSchedule(scheduleData, allianceData, leagueArray['withoutSID'], true);
        if ((ballType == 'fv' || ballType == 'sc') && $('#scheduleTop table').length > 0) {
            $('#scheduleMiddle > table.scTable').addClass('scTop');
        }
        UnMask();
    },
    50);
}
function ShowSoccerOption() {
    $('#soccerOption').toggle();
}
function ShowOrHideYelloCard() {
    Mask();
    if ($('#ckbYellowCard').hasClass('ckbOK')) {
        soccerCards['yellowCard'] = 0;
        $('#ckbYellowCard').removeClass('ckbOK');
    } else {
        soccerCards['yellowCard'] = 1;
        $('#ckbYellowCard').addClass('ckbOK');
    }
    setTimeout(function() {
        $('#scheduleMiddle > table.scTable > tbody > tr > td.teamName > span.yellowCards').add('#scheduleTop > table.scTable > tbody > tr > td.teamName > span.yellowCards').add('#scheduleBottom > table.scTable > tbody > tr > td.teamName > span.yellowCards').each(function() {
            if ($(this).text() != '') {
                if (soccerCards['yellowCard'] == 0) {
                    $(this).addClass('hidden');
                } else {
                    $(this).removeClass('hidden');
                }
            }
        });
    },
    50);
    UnMask();
}
function ShowOrHideStadings(e) {
    Mask();
    if ($('#ckbStadings').hasClass('ckbOK')) {
        soccerCards['stadings'] = 0;
        $('#ckbStadings').removeClass('ckbOK');
    } else {
        soccerCards['stadings'] = 1;
        $('#ckbStadings').addClass('ckbOK');
    }
    if (langFont['Font_Langue'] != 'en') {
        setTimeout(function() {
            $('#scheduleMiddle > table.scTable > tbody > tr > td.teamName > span.ranking').add('#scheduleTop > table.scTable > tbody > tr > td.teamName > span.ranking').add('#scheduleBottom > table.scTable > tbody > tr > td.teamName > span.ranking').each(function() {
                if ($(this).text() != '') {
                    if (soccerCards['stadings'] == 0) {
                        $(this).addClass('hidden');
                    } else {
                        $(this).removeClass('hidden');
                    }
                }
            });
        },
        50)
    }
    UnMask();
}
function ShowOrHideCorners() {
    Mask();
    if ($('#ckbCorner').hasClass('ckbOK')) {
        soccerCards['corner'] = 0;
        $('#ckbCorner').removeClass('ckbOK');
    } else {
        soccerCards['corner'] = 1;
        $('#ckbCorner').addClass('ckbOK');
    }
    setTimeout(function() {
        $('#scheduleMiddle > table.scTable > tbody > tr.jq').add('#scheduleTop > table.scTable > tbody > tr.jq').add('#scheduleBottom > table.scTable > tbody > tr.jq').each(function() {
            if (soccerCards['corner'] == 0) {
                $(this).addClass('hidden');
            } else {
                $(this).removeClass('hidden');
            }
        });
    },
    50);
    UnMask();
}
function ShowOrHideAnnounces(e) {
    Mask();
    if ($('#ckbAnnounces').hasClass('ckbOK')) {
        soccerCards['announces'] = 0;
        $('#ckbAnnounces').removeClass('ckbOK');
        $('#scheduleRemind').addClass('hidden');
    } else {
        soccerCards['announces'] = 1;
        $('#ckbAnnounces').addClass('ckbOK');
    }
    UnMask();
}
function ToTop() {
    $('#scheduleBlock > div > div').scrollTop(0);
}
function ScrollPage() {
    var scrollTop = $('#scheduleBlock > div > div').scrollTop();
    var topHeight = $('#scheduleTop').css('height').split('px')[0];
    if (scrollTop > 310) {
        $('#goTop').fadeIn();
    } else {
        $('#goTop').fadeOut();
    }
    var changeBlock = null;
    if (ballType == 'sc' && topHeight != 0) {
        changeBlock = scrollTop < topHeight ? '#scheduleTop': '#scheduleMiddle';
    } else if (ballType == 'fv' && $('#scheduleBlock > .scrollbar-inner .scTable').length > 0) {
        var hideSettingTop = $('#hideSetting').offset().top + 40;
        var topLastTr = $('#scheduleTop .scTable tr:last-child').offset() == undefined ? null: $('#scheduleTop .scTable tr:last-child').offset().top;
        var middleThRowTop = $('#scheduleMiddle #sc_thRow').offset() == undefined ? null: $('#scheduleMiddle #sc_thRow').offset().top;
        var middleLastTr = $('#scheduleMiddle .scTable tr:last-child').offset() == undefined ? null: $('#scheduleMiddle .scTable tr:last-child').offset().top;
        if (topLastTr > hideSettingTop) {
            $('#fixedTitle').show();
            changeBlock = '#scheduleTop';
        } else if ((middleLastTr > hideSettingTop)) {
            if ($('#scheduleTop > table').length > 0 && middleThRowTop > hideSettingTop) {
                $('#fixedTitle').hide();
                changeBlock = null;
            } else {
                $('#fixedTitle').show();
                changeBlock = '#scheduleMiddle';
            }
        } else {
            $('#fixedTitle').hide();
            changeBlock = null;
        }
    }
    if (changeBlock) {
        if ($(changeBlock + ' #sc_thRow .check > div').hasClass('ckbOK')) {
            $('#fixedTitle > span.check > span').addClass('ckbOK');
        } else {
            $('#fixedTitle > span.check > span').removeClass('ckbOK');
        }
    }
}
function JoinFavority(url, title, msg) {
    try {
        window.external.addFavorite(favoriteSetting['url'], favoriteSetting['title']);
    } catch(e) {
        try {
            window.external.AddFavorite(favoriteSetting['title'], favoriteSetting['url']);
        } catch(e) {
            try {
                window.sidebar.addPanel(favoriteSetting['title'], favoriteSetting['url'], "");
            } catch(e) {
                alert(favoriteSetting['msg']);
            }
        }
    }
}
function PageReload() {
    window.location.reload(true);
}
function ShowQrMobile() {
    var top = (window.screen.availHeight - 720) / 2;
    var left = (window.screen.availWidth - 910) / 2;
    window.open('/sport/QrMobile.aspx', 'mobile', 'height=690, width=890, top=' + top + ', left=' + left + ', toolbar=no, resizable=yes');
}
function ActionUpdate(data) {
    var actionTime = new Date().getTime();
    lightScanner['actionRecord'][actionTime] = 'update';
    clearInterval(lightScanner['timer']);
    recentSN = data['sn'];
    if (data['menu']) {
        var menuSet = [];
        for (var i = 0; i < data['menu'].length; i++) {
            var tempType = Object.keys(data['menu'][i])[0];
            menuSet.push(tempType);
        }
        if (ballType != 'fv' && $.inArray(ballType, menuSet) < 0) {
            if ($.inArray(defaultType, menuSet) >= 0) {
                ChangeType(defaultType);
            } else {
                ChangeType('sc');
            }
            return;
        }
        DrawMenuList(data['menu'], ballType);
    }
    if (data['gameCount'] && ballType != 'fv') {
        SetDateOption(data['gameCount']['date']);
    }
    var isScheduleRedraw = false;
    var isALRedraw = false;
    var isMenuRedraw = false;
    var insertSet = [];
    var deleteSet = {
        'gid': [],
        'leagueID': []
    };
    if (data['league']) {
        var updateData = data['league'];
        for (var i = 0; i < updateData.length; i++) {
            var pack = updateData[i];
            var leagueID = pack['id'];
            if (allianceData[leagueID]) {
                var leagueKeys = Object.keys(pack);
                leagueKeys.remove('id');
                for (var j = 0; j < leagueKeys.length; j++) {
                    var keyName = leagueKeys[j];
                    if (!allianceData[leagueID][keyName + '_sn'] || allianceData[leagueID][keyName + '_sn'] < data['sn']) {
                        allianceData[leagueID][keyName + '_sn'] = data['sn'];
                        allianceData[leagueID][keyName] = pack[keyName];
                        if (keyName == 'n') {
                            isALRedraw = true;
                            $('#aid_' + leagueID).text(pack['n']);
                        } else if (keyName == 'u') {
                            if (pack['u']) {
                                $('#aid_' + leagueID).removeClass('noHref');
                                $('#aid_' + leagueID).attr("href", pack['u']);
                            } else if (pack['u'] == '') {
                                $('#aid_' + leagueID).addClass('noHref');
                                $('#aid_' + leagueID).removeAttr("href");
                            }
                        } else if (keyName == 's') {
                            allianceData[leagueID]['gidSet'].map(function(gid) {
                                insertSet.push(gid);
                                deleteSet['gid'].push(gid);
                                deleteSet['leagueID'].push(leagueID);
                            });
                        }
                    } else {
                        delete updateData[i][keyName];
                    }
                }
            } else {
                console.info(leagueID + ', "aID" is not found!!!');
            }
        }
    }
    if (data['aIndex']) {
        isScheduleRedraw = true;
        leagueArray['withoutSID'] = data['aIndex'];
        leagueArray['withSID'] = $.extend([], leagueArray['withoutSID']).sort(function(a, b) {
            if (allianceData[a]['s'] != allianceData[b]['s']) {
                return allianceData[a]['s'] > allianceData[b]['s'] ? 1 : -1;
            } else {
                return $.inArray(a, leagueArray['withoutSID']) > $.inArray(b, leagueArray['withoutSID']) ? 1 : -1;
            }
        });
        isALRedraw = true;
    }
    if (isALRedraw) {
        if ($('#boundary:visible').length > 0) {
            SetLeagueOption();
        } else {
            $('#leagueOption').offset({
                top: -500,
                left: -500
            });
            $('#boundary').show();
            SetLeagueOption();
            $('#boundary').hide();
            $('#leagueOption').removeAttr('style');
        }
    }
    if (data['schedule']) {
        var updateData = data['schedule'];
        for (var i = 0; i < updateData.length; i++) {
            var gid = updateData[i]['pk'];
            if (scheduleData[gid]) {
                var leagueID = scheduleData[gid]['aID'];
                var gameInfo = updateData[i];
                var isGameSort = false;
                var isSCRedraw = false;
                if (!tempScheduleData[gid]) {
                    tempScheduleData[gid] = $.extend({},
                    scheduleData[gid])
                }
                $.each(gameInfo,
                function(keyName) {
                    if (keyName != 'pk') {
                        if (!scheduleData[gid][keyName + '_sn'] || scheduleData[gid][keyName + '_sn'] < data['sn']) {
                            scheduleData[gid][keyName + '_sn'] = data['sn'];
                            scheduleData[gid][keyName] = gameInfo[keyName];
                            if (keyName == 'gd' || keyName == 'gst') {
                                isGameSort = true;
                                if (keyName == 'gst') {
                                    isMenuRedraw = true;
                                }
                            }
                            if (allianceData[leagueID]['type'] == 'sc' && (keyName == 'jq' || keyName == 'gs')) {
                                if (keyName == 'jq') {
                                    tempScheduleData[gid][keyName] = scheduleData[gid][keyName];
                                }
                                isScheduleRedraw = true;
                                isSCRedraw = true;
                            }
                        } else {
                            delete gameInfo[keyName];
                        }
                    }
                });
                if (isGameSort || isSCRedraw) {
                    if ($.inArray(gid, insertSet) < 0) {
                        insertSet.push(gid);
                    }
                    if ($.inArray(gid, deleteSet['gid']) < 0) {
                        deleteSet['gid'].push(gid);
                        deleteSet['leagueID'].push(leagueID);
                    }
                }
                if (isGameSort) {
                    isScheduleRedraw = true;
                    allianceData[leagueID]['gidSet'] = $.extend([], allianceData[leagueID]['gidSet']).sort(function(a, b) {
                        if (new Date(scheduleData[a]['gd']).getTime() != new Date(scheduleData[b]['gd']).getTime()) {
                            return new Date(scheduleData[a]['gd']).getTime() > new Date(scheduleData[b]['gd']).getTime() ? 1 : -1;
                        } else {
                            return $.inArray(a, allianceData[leagueID]['gidSet']) > $.inArray(b, allianceData[leagueID]['gidSet']) ? 1 : -1;
                        }
                    });
                }
            } else {
                updateData[i]['notValid'] = true;
                console.info(gid + ', "pk" is not found!!!');
            }
        }
    }
    if (isMenuRedraw) {
        DrawMenuList('menuDetailModify', ballType);
    }
    if (isScheduleRedraw) {
        if (ballType != 'fv') {
            FilterSchedule(ballType, scheduleData, allianceData, 3);
        } else {
            FuncFavorite.DrawFavoriteSchedule(scheduleData, allianceData, leagueArray['withoutSID'], false);
        }
        RemoveSchedule(deleteSet);
        InsertSchedule(insertSet);
        ResetHeaderAndRowColor();
        if ($('#scheduleBlock > div > div > div > table').length == 0) {
            $('#scheduleNoData').show();
        }
        if ((ballType == 'fv' || ballType == 'sc') && $('#scheduleTop > table').length > 0) {
            $('#scheduleMiddle > table.scTable').addClass('scTop');
        }
        GameMarked();
    }
    if (data['schedule']) {
        var nowTime = new Date().getTime();
        var updateData = data['schedule'];
        $.each(updateData,
        function(keyName) {
            if (!updateData[keyName]['notValid']) {
                var targetData = '';
                var leagueID = scheduleData[updateData[keyName]['pk']]['aID'];
                if (allianceData[leagueID] && updateData[keyName]) {
                    if (ballType == 'fv' || ballType == allianceData[leagueID]['type']) {
                        SetBallFunc(allianceData[leagueID]['type']);
                        ballFunc.UpdateGameData(updateData[keyName], nowTime);
                    }
                }
            }
        });
    }
    if (data['prompt']) {
        var nowTime = new Date().getTime();
        var tempPrompt = [];
        for (var i = 0; i < data['prompt'].length; i++) {
            var gid = data['prompt'][i]['pk'];
            if ($('#scheduleBlock > div > div > div > table[gt="sc"]').length > 0 && $('#' + gid + '_mainRow').length > 0) {
                tempPrompt.push(data['prompt'][i]);
            }
        }
        if (tempPrompt.length <= 10 && tempPrompt.length > 0) {
            updateItem['#goalMsg']['prompt'] = updateItem['#goalMsg']['prompt'].concat(tempPrompt);
        }
    }
    tempScheduleData = {};
    delete lightScanner['actionRecord'][actionTime];
    if ($.isEmptyObject(lightScanner['actionRecord'])) {
        lightScanner['timer'] = setTimeout(removeHighLight, 200);
    }
}
function removeHighLight() {
    var nowTime = new Date().getTime();
    $.each(updateItem,
    function(id) {
        if (id == '#goalMsg') {
            if (updateItem['#goalMsg']['prompt'].length > 0 && !(updateItem['#goalMsg']['time'] != null && (nowTime - updateItem['#goalMsg']['time']) < 1000)) {
                FuncSoccer.updateMessage(updateItem['#goalMsg']['prompt'][0], nowTime, true);
                updateItem['#goalMsg']['prompt'].splice(0, 1);
            } else if (nowTime - updateItem['#goalMsg']['time'] > 30000) {
                $(id).empty();
                $('#scheduleRemind').addClass('hidden');
                $('#scheduleRemind').removeAttr('style');
                updateItem[id]['time'] = null;
                updateItem[id]['prompt'] = [];
            }
        } else if (nowTime - updateItem[id] >= 5000) {
            $(id).removeClass('highlight');
            if (! (id.indexOf('ra') <= 0 && id.indexOf('rb') <= 0 && id.indexOf('ga') <= 0 && id.indexOf('gb') <= 0)) {
                $(id).removeClass('black');
            }
            delete updateItem[id];
        }
    });
    if ($.isEmptyObject(lightScanner['actionRecord'])) {
        lightScanner['timer'] = setTimeout(removeHighLight, 200);
    }
}
function ActionAddGame(data) {
    var actionTime = new Date().getTime();
    lightScanner['actionRecord'][actionTime] = 'add';
    clearInterval(lightScanner['timer']);
    recentSN = data['sn'];
    viewPosition = $('#scheduleBlock > div > div').scrollTop();
    var isMenuRedraw = (gameDate['string'] == nowDate['string']) ? true: false;
    var insertSet = [];
    var deleteSet = {
        'gid': [],
        'leagueID': []
    };
    var resultData = data['schedule'];
    var resultLeague = [];
    resultLeague = resultData.map(function(game) {
        return game['aID'];
    });
    resultLeague = resultLeague.filter(function(element, index, arr) {
        return arr.indexOf(element) === index;
    });
    if (ballType != 'fv') {
        for (var i = 0; i < resultLeague.length; i++) {
            if (resultLeague[i].split('_')[0] != ballType) {
                return;
            }
        }
    }
    if (data['league']) {
        for (var i = 0; i < data['league'].length; i++) {
            var leagueID = data['league'][i]['id'];
            if (!allianceData[leagueID]) {
                allianceData[leagueID] = data['league'][i];
            } else {
                allianceData[leagueID] = $.extend(allianceData[leagueID], data['league'][i]);
            }
        }
    }
    if (data['aIndex']) {
        leagueArray['withoutSID'] = data['aIndex'];
        leagueArray['withSID'] = $.extend([], leagueArray['withoutSID']).sort(function(a, b) {
            if (allianceData[a]['s'] != allianceData[b]['s']) {
                return allianceData[a]['s'] > allianceData[b]['s'] ? 1 : -1;
            } else {
                return $.inArray(a, leagueArray['withoutSID']) > $.inArray(b, leagueArray['withoutSID']) ? 1 : -1;
            }
        });
        if ($('#boundary:visible').length > 0) {
            SetLeagueOption();
        } else {
            $('#leagueOption').offset({
                top: -500,
                left: -500
            });
            $('#boundary').show();
            SetLeagueOption();
            $('#boundary').hide();
            $('#leagueOption').removeAttr('style');
        }
    }
    resultLeague = resultLeague.map(function(leagueID) {
        return allianceData[leagueID];
    });
    for (var i = 0; i < resultData.length; i++) {
        var gid = resultData[i]['pk'];
        var leagueID = resultData[i]['aID'];
        if (allianceData[leagueID]) {
            scheduleData[gid] = resultData[i];
            tempScheduleData[gid] = resultData[i];
            if (allianceData[leagueID]['gidSet']) {
                allianceData[leagueID]['gidSet'].push(gid);
            } else {
                if (!allianceData[leagueID]['type']) {
                    allianceData[leagueID]['type'] = gid.split('_')[0];
                }
                allianceData[leagueID]['gidSet'] = [];
                allianceData[leagueID]['gidSet'].push(gid);
            }
            allianceData[leagueID]['gidSet'] = allianceData[leagueID]['gidSet'].filter(function(element, index, arr) {
                return arr.indexOf(element) === index;
            });
            deleteSet['gid'].push(gid);
            deleteSet['leagueID'].push(leagueID);
            insertSet.push(gid);
        }
    }
    for (var i = 0; i < resultLeague.length; i++) {
        var leagueID = resultLeague[i]['id'];
        allianceData[leagueID]['gidSet'] = $.extend([], allianceData[leagueID]['gidSet']).sort(function(a, b) {
            if (new Date(scheduleData[a]['gd']).getTime() != new Date(scheduleData[b]['gd']).getTime()) {
                return new Date(scheduleData[a]['gd']).getTime() > new Date(scheduleData[b]['gd']).getTime() ? 1 : -1;
            } else {
                return $.inArray(a, allianceData[leagueID]['gidSet']) > $.inArray(b, allianceData[leagueID]['gidSet']) ? 1 : -1;
            }
        });
    }
    var count = Object.keys(scheduleData).length;
    $('#dateOption > a[name="' + gameDate['string'].replaceAll('/', '') + '"] > span.rightDate').text(count);
    $('#gameCount').text(count);
    if (isMenuRedraw) {
        DrawMenuList('menuDetailModify', ballType);
    }
    ShowOrHideElement();
    if (ballType != 'fv') {
        FilterSchedule(ballType, scheduleData, allianceData, 3);
    } else {
        FuncFavorite.DrawFavoriteSchedule(scheduleData, allianceData, leagueArray['withoutSID'], false);
        RemoveSchedule(deleteSet);
    }
    InsertSchedule(insertSet);
    ResetHeaderAndRowColor();
    if ((ballType == 'fv' || ballType == 'sc') && $('#scheduleTop > table').length > 0) {
        $('#scheduleMiddle > table.scTable').addClass('scTop');
    }
    GameMarked();
    tempScheduleData = {};
    $('#scheduleBlock > div > div').scrollTop(viewPosition);
    delete lightScanner['actionRecord'][actionTime];
    if ($.isEmptyObject(lightScanner['actionRecord'])) {
        lightScanner['timer'] = setTimeout(removeHighLight, 200);
    }
}
function ActionDelGame(data) {
    var actionTime = new Date().getTime();
    lightScanner['actionRecord'][actionTime] = 'del';
    clearInterval(lightScanner['timer']);
    recentSN = data['sn'];
    viewPosition = $('#scheduleBlock > div > div').scrollTop();
    var delArray = data['value'];
    var deleteSet = {
        'gid': [],
        'leagueID': []
    };
    var isALRedraw = false;
    var isAllLeagueDel = false;
    var isMenuRedraw = false;
    delArray.map(function(pack) {
        var gid = pack['pk'];
        var favoriteIndex = jQuery.inArray(gid, FuncFavorite.ScheduleFVGroup['pk']);
        if (pack['bool'] == 1 && favoriteIndex >= 0) {
            FuncFavorite.ScheduleFVGroup['date'].splice(favoriteIndex, 1);
            FuncFavorite.ScheduleFVGroup['pk'].splice(favoriteIndex, 1);
            isMenuRedraw = true;
        }
        SetCookie('fvPK', FuncFavorite.ScheduleFVGroup['pk']);
        SetCookie('fvDate', FuncFavorite.ScheduleFVGroup['date']);
        if (ballType == 'fv' && pack['bool'] == 0) {
            return false;
        } else if (scheduleData[gid]) {
            var leagueID = scheduleData[gid]['aID'];
            delete scheduleData[gid];
            deleteSet['gid'].push(gid);
            deleteSet['leagueID'].push(leagueID);
            if ($.inArray('#' + gid + '_mainRow', gameMarked['checked']) >= 0) {
                gameMarked['checked'].remove('#' + gid + '_mainRow');
            }
            if ($.inArray(gid, gameMarked['inExclude']) >= 0) {
                gameMarked['inExclude'].remove(gid);
            }
            if ($.inArray(gid, gameMarked['inKeep']) >= 0) {
                gameMarked['inKeep'].remove(gid);
            }
            if ($.inArray(gid, gameMarked['inTop']) >= 0) {
                gameMarked['inTop'].remove(gid);
            }
            allianceData[leagueID]['gidSet'].remove(gid);
            if (allianceData[leagueID]['gidSet'].length == 0) {
                delete allianceData[leagueID];
                leagueArray['withoutSID'].remove(leagueID);
                leagueArray['withSID'].remove(leagueID);
                isALRedraw = true;
                sortOption['league'].remove(leagueID);
                if (sortOption['league'].length == 0 || leagueArray['withoutSID'].length == sortOption['league'].length) {
                    sortOption['league'] = ['All'];
                    isAllLeagueDel = true;
                }
                var getDate = ballType == 'fv' ? 'fv': ballType + '_' + gameDate['string'].substr(5, 5);
                SetCookie(getDate, sortOption['league']);
            }
            if (gameDate['string'] == nowDate['string']) {
                isMenuRedraw = true;
            }
            return leagueID;
        } else {
            return false;
        }
    });
    if (isAllLeagueDel) {
        if (ballType == 'fv') {
            FuncFavorite.DrawFavoriteSchedule(scheduleData, allianceData, leagueArray['withoutSID'], true);
        } else {
            var filterData = FilterSchedule(ballType, scheduleData, allianceData, 1);
            DrawSchedule(filterData, ballType, true, true);
        }
    } else {
        RemoveSchedule(deleteSet);
        ResetHeaderAndRowColor() if ($('#scheduleBlock > div > div > div > table').length == 0) {
            $('#scheduleNoData').show();
        }
    }
    if (isALRedraw) {
        if ($('#boundary:visible').length > 0) {
            SetLeagueOption();
        } else {
            $('#leagueOption').offset({
                top: -500,
                left: -500
            });
            $('#boundary').show();
            SetLeagueOption();
            $('#boundary').hide();
            $('#leagueOption').removeAttr('style');
        }
    }
    var count = Object.keys(scheduleData).length;
    $('#dateOption > a[name="' + gameDate['string'].replaceAll('/', '') + '"] > span.rightDate').text(count);
    $('#gameCount').text(count);
    if (isMenuRedraw) {
        DrawMenuList('menuDetailModify', ballType);
    }
    ShowOrHideElement();
    if ((ballType == 'fv' || ballType == 'sc') && $('#scheduleTop > table').length > 0) {
        $('#scheduleMiddle > table.scTable').addClass('scTop');
    }
    GameMarked();
    $('#scheduleBlock > div > div').scrollTop(viewPosition);
    delete lightScanner['actionRecord'][actionTime];
    if ($.isEmptyObject(lightScanner['actionRecord'])) {
        lightScanner['timer'] = setTimeout(removeHighLight, 200);
    }
}
function RemoveSchedule(deleteSet) {
    for (var i = 0; i < deleteSet['gid'].length; i++) {
        $('#scheduleBlock > div > div > div > table > tbody > tr[gid^="' + deleteSet['gid'][i] + '"]').remove();
        if (deleteSet['gid'][i].split('_')[0] == 'sc') {
            if ($('#scheduleTop > table.scTable > tbody > tr').length <= 1) {
                $('#scheduleTop > table.scTable').remove();
                if (ballType == 'sc') {
                    $('#scheduleMiddle > table.scTable').removeClass('scTop');
                }
            }
            if ($('#scheduleMiddle > table.scTable > tbody > tr').length <= 1) {
                $('#scheduleMiddle > table.scTable').remove();
            }
            if ($('#scheduleBlock > div > div > div > table.scTable').length == 0) {
                $('#fixedTitle').hide();
            }
        } else {
            $('#scheduleBlock > div > div > div > table[rel ="' + deleteSet['leagueID'][i] + '"] > tbody > tr:first').removeClass('hidden');
            $('#scheduleBlock > div > div > div > table[rel ="' + deleteSet['leagueID'][i] + '"] > tbody').each(function() {
                if ($(this).children().length == 0) {
                    if ($(this).parent().prev('table').attr('rel') == $(this).parent().next('table').attr('rel')) {
                        $(this).parent().next('table').children('tbody').children('tr:first').addClass('hidden');
                        var result = $(this).parent().next('table').children('tbody').html();
                        $(this).parent().prev('table').children('tbody').append(result);
                        $(this).parent().next('table').remove();
                    }
                    $(this).parent().remove();
                }
            });
        }
        if ($('#scheduleTop > table').length == 0 && ballType == 'fv' && $('#scheduleMiddle > table.scTable').length > 0) {
            $('#scheduleMiddle > table.scTable').removeClass('scTop');
        }
    }
}
function InsertSchedule(insertSet) {
    if (insertSet.length > 0) {
        insertSet = $.extend([], insertSet).sort(function(a, b) {
            if (ballType == 'fv' || ballType == 'sc') {
                return $.inArray(a, scheduleArray['S']) > $.inArray(b, scheduleArray['S']) ? 1 : -1;
            } else if (scheduleData[a]['gst'] == scheduleData[b]['gst']) {
                var tempGst = scheduleData[a]['gst'] == 'X' ? 'S': scheduleData[a]['gst'];
                return $.inArray(a, scheduleArray[tempGst]) > $.inArray(b, scheduleArray[tempGst]) ? 1 : -1;
            } else {
                var gstSet = ['top', 'S', 'E'];
                var gstA = scheduleData[a]['gst'] == 'X' ? 'S': scheduleData[a]['gst'];
                var gstB = scheduleData[b]['gst'] == 'X' ? 'S': scheduleData[b]['gst'];
                return $.inArray(gstA, gstSet) > $.inArray(gstA, gstSet) ? 1 : -1;
            }
        });
    }
    for (var i = 0; i < insertSet.length; i++) {
        var gid = scheduleData[insertSet[i]]['pk'];
        var gst = scheduleData[insertSet[i]]['gst'] == 'X' ? 'S': scheduleData[insertSet[i]]['gst'];
        var type = gid.split('_')[0];
        if (ballType == 'fv' || ballType == 'sc') {
            gst = 'S';
        }
        if ($.inArray(gid, scheduleArray['top']) >= 0) {
            gst = 'top';
        }
        var isDown = true;
        var appendIndex = $.inArray(gid, scheduleArray[gst]);
        if (appendIndex < 0) {
            continue;
        }
        var preID = appendIndex - 1 >= 0 ? scheduleArray[gst][appendIndex - 1] : 0;
        var nextID = 0;
        if (appendIndex + 1 <= scheduleArray[gst].length - 1) {
            for (var j = appendIndex + 1; j < scheduleArray[gst].length; j++) {
                if ($.inArray(scheduleArray[gst][j], insertSet) < 0) {
                    nextID = scheduleArray[gst][j];
                    break;
                }
            }
        }
        var appendNode = gst == 'top' ? '#scheduleTop': (gst == 'S' ? '#scheduleMiddle': '#scheduleBottom');
        var htmlText = '';
        if (type == 'sc') {
            var tempObj = [];
            tempObj.push($.extend({},
            tempScheduleData[gid]));
            if (preID == 0 && nextID == 0) {
                $('#scheduleNoData').hide();
                htmlText = FuncSoccer.DrawTable(tempObj, allianceData, gst, true);
                $(appendNode).html(htmlText);
            } else if ($(appendNode + ' table.scTable').length == 0) {
                htmlText = FuncSoccer.DrawTable(tempObj, allianceData, gst, true);
                if (preID != 0) {
                    $(appendNode + ' tr[id^="' + preID + '"]:last').parents('table').after(htmlText);
                } else {
                    $(appendNode + ' tr[id^="' + nextID + '"]:first').parents('table').before(htmlText);
                }
            } else {
                htmlText = FuncSoccer.DrawTable(tempObj, allianceData, gst, false);
                if (preID != 0) {
                    $(appendNode + ' tr[id^="' + preID + '"]:last').after(htmlText);
                } else {
                    $(appendNode + ' tr[id^="' + nextID + '"]:first').before(htmlText);
                }
            }
        } else {
            var usePreOrNext = 0;
            SetBallFunc(type);
            var scheduleInfo = allianceData[scheduleData[gid]['aID']];
            var tempObj = $.extend({},
            tempScheduleData[gid]);
            if (preID != 0) {
                usePreOrNext = scheduleData[preID]['aID'] == scheduleData[gid]['aID'] ? 1 : usePreOrNext;
            }
            if (nextID != 0) {
                usePreOrNext = scheduleData[nextID]['aID'] == scheduleData[gid]['aID'] ? 2 : usePreOrNext;
            }
            if (usePreOrNext == 0) {
                if (preID != 0 && nextID != 0) {
                    usePreOrNext = scheduleData[preID]['aID'] == scheduleData[nextID]['aID'] ? 3 : usePreOrNext;
                }
                if (type == 'bk') {
                    htmlText = '<table rel="' + scheduleInfo['id'] + '" al="' + scheduleInfo['o'] + '" gt="' + type + '" sort="' + scheduleInfo['s'] + '">';
                } else {
                    htmlText = '<table rel="' + scheduleInfo['id'] + '" al="' + scheduleInfo['n'] + '" gt="' + type + '" sort="' + scheduleInfo['s'] + '">';
                }
                htmlText += '<caption>';
                var regExp = /^(?:([A-Za-z]+):)?(\/{0,3})([0-9.\-A-Za-z]+)(?::(\d+))?(?:\/([^?#]*))?(?:\?([^#]*))?(?:#(.*))?$/;
                var ballIcon = '';
                if (ballType == 'fv') {
                    if (type == 'tw') {
                        ballIcon = '<img src="/images/sport/ic_bb.png" class="ballIcon">';
                    } else if (type == 'bv') {
                        ballIcon = '<img src="/images/sport/ic_vl.png" class="ballIcon">';
                    } else {
                        ballIcon = '<img src="/images/sport/ic_' + type + '.png" class="ballIcon">';
                    }
                }
                if (scheduleInfo['u'] && regExp.test(scheduleInfo['u'])) {
                    htmlText += ballIcon + '<a target="_blank" href="' + scheduleInfo['u'] + '" id="aid_' + scheduleInfo['id'] + '">' + scheduleInfo['n'] + '</a>';
                } else {
                    htmlText += ballIcon + '<a target="_blank" id="aid_' + scheduleInfo['id'] + '"  class="noHref">' + scheduleInfo['n'] + '</a>';
                }
                htmlText += '</caption>';
                htmlText += ballFunc.AddGameData((scheduleInfo['o'] ? scheduleInfo['o'] : ''), tempObj, 1, '', false);
                htmlText += '</table>';
                if (preID == 0 && nextID == 0) {
                    $('#scheduleNoData').hide();
                    $(appendNode).html(htmlText);
                } else {
                    if (usePreOrNext == 3) {
                        var tempTable = $(appendNode + ' tr[id^="' + preID + '"]:last').parents('table');
                        var tableHead = $(tempTable)[0].outerHTML.split('<tr')[0];
                        var trSet = $(tempTable).children('tbody').children('tr');
                        var tableHtml = tableHead;
                        var splitFlag = $(appendNode + ' tr[id^="' + preID + '"]:last').attr('id');
                        for (var k = 0; k < trSet.length; k++) {
                            tableHtml += $(trSet[k])[0].outerHTML;
                            if (splitFlag == $(trSet[k]).attr('id')) {
                                tableHtml += '</tbody></table>' + htmlText + tableHead;
                            }
                        }
                        tableHtml += '</tbody></table>';
                        $(tempTable).hide();
                        $(tempTable).after(tableHtml);
                        $(tempTable).remove();
                    } else if (preID != 0) {
                        $(appendNode + ' tr[id^="' + preID + '"]:last').parents('table').after(htmlText);
                    } else {
                        $(appendNode + ' tr[id^="' + nextID + '"]:last').parents('table').before(htmlText);
                    }
                }
            } else {
                htmlText = ballFunc.AddGameData((scheduleInfo['o'] ? scheduleInfo['o'] : ''), tempObj, 1, '', false);
                if (usePreOrNext == 1) {
                    $(appendNode + ' tr[id^="' + preID + '"]:last').after(htmlText);
                } else {
                    $(appendNode + ' tr[id^="' + nextID + '"]:first').before(htmlText);
                }
            }
        }
    }
}
function ResetHeaderAndRowColor() {
    var tableSet = $('#scheduleTop > table').add('#scheduleMiddle > table').add('#scheduleBottom > table');
    for (var i = 0; i < tableSet.length; i++) {
        var trSet = $(tableSet[i]).children('tbody').children('tr');
        var trGid = [];
        if ($(tableSet[i]).attr('gt') != 'sc') {
            $(tableSet[i]).children('tbody').children('tr[id$="headerRow"]').addClass('hidden');
            $(tableSet[i]).children('tbody').children('tr[id$="headerRow"]:first').removeClass('hidden');
        }
        $(tableSet[i]).children('tbody').children('tr').removeClass('even');
        var gid = 0;
        var gameCount = $(tableSet[i]).attr('gt') == 'sc' ? 0 : 1;
        for (var j = 0; j < trSet.length; j++) {
            var tempGid = $(trSet[j]).attr('gid');
            if (tempGid != gid && gid + 'c' != tempGid) {
                trGid.push(tempGid);
            }
            gid = tempGid;
        }
        for (var k = 0; k < trGid.length; k++) {
            if (gameCount % 2 == 0) {
                $(tableSet[i]).children('tbody').children('tr[id^="' + trGid[k] + '"]').addClass('even');
            }
            gameCount++;
        }
    }
}
function ActionResetSN() {
    recentSN = 0;
    Object.keys(allianceData).map(function(leagueID) {
        var keys = Object.keys(allianceData[leagueID]);
        for (var i = 0; i < keys.length; i++) {
            if (keys[i].indexOf('_sn') > 0) {
                allianceData[leagueID][keys[i]] = recentSN;
            } else if (keys[i] == 'id' || keys[i] == 'type' || keys[i] == 'gidSet') {
                continue;
            } else {
                allianceData[leagueID][keys[i] + '_sn'] = recentSN;
            }
        }
    });
    Object.keys(scheduleData).map(function(gid) {
        var keys = Object.keys(scheduleData[gid]);
        for (var i = 0; i < keys.length; i++) {
            if (keys[i].indexOf('_sn') > 0) {
                scheduleData[gid][keys[i]] = recentSN;
            } else if (keys[i] == 'pk' || keys[i] == 'aID') {
                continue;
            } else {
                scheduleData[gid][keys[i] + '_sn'] = recentSN;
            }
        }
    });
}
function ActionMt() {
    UnMask();
    $('#maintBlock').show();
}
function ActionMtover() {
    $('#maintLink').attr('href', window.location.href);
    $('#maintOverBlock').show();
}